
- Fortran 教程
- Fortran - 首頁
- Fortran - 概述
- Fortran - 環境設定
- Fortran - 基本語法
- Fortran - 資料型別
- Fortran - 變數
- Fortran - 常量
- Fortran - 運算子
- Fortran - 決策
- Fortran - 迴圈
- Fortran - 數字
- Fortran - 字元
- Fortran - 字串
- Fortran - 陣列
- Fortran - 動態陣列
- Fortran - 派生資料型別
- Fortran - 指標
- Fortran - 基本輸入輸出
- Fortran - 檔案輸入輸出
- Fortran - 過程
- Fortran - 模組
- Fortran - 內在函式
- Fortran - 數值精度
- Fortran - 程式庫
- Fortran - 程式設計風格
- Fortran - 除錯程式
- Fortran 資源
- Fortran - 快速指南
- Fortran - 有用資源
- Fortran - 討論
Fortran - 基本語法
Fortran 程式由程式單元的集合組成,例如主程式、模組和外部子程式或過程。
每個程式包含一個主程式,並且可以包含或不包含其他程式單元。主程式的語法如下所示:
program program_name implicit none ! type declaration statements ! executable statements end program program_name
Fortran 中的一個簡單程式
讓我們編寫一個程式來新增兩個數字並列印結果:
program addNumbers ! This simple program adds two numbers implicit none ! Type declarations real :: a, b, result ! Executable statements a = 12.0 b = 15.0 result = a + b print *, 'The total is ', result end program addNumbers
編譯並執行上述程式時,會產生以下結果:
The total is 27.0000000
請注意:
所有 Fortran 程式都以關鍵字program開頭,以關鍵字end program結尾,後跟程式名稱。
implicit none語句允許編譯器檢查所有變數型別是否已正確宣告。您必須始終在每個程式的開頭使用implicit none。
Fortran 中的註釋以感嘆號 (!) 開頭,因為此後的所有字元(字元字串除外)都將被編譯器忽略。
print *命令在螢幕上顯示資料。
程式碼行的縮排是保持程式可讀性的良好實踐。
Fortran 允許使用大寫和小寫字母。Fortran 不區分大小寫,但字串文字除外。
基礎知識
Fortran 的基本字元集包含:
- 字母 A ... Z 和 a ... z
- 數字 0 ... 9
- 下劃線 (_) 字元
- 特殊字元 = : + 空格 - * / ( ) [ ] , . $ ' ! " % & ; < > ?
標記由基本字元集中的字元組成。標記可以是關鍵字、識別符號、常量、字串文字或符號。
程式語句由標記組成。
識別符號
識別符號是用於識別變數、過程或任何其他使用者定義專案的名稱。Fortran 中的名稱必須遵循以下規則:
長度不能超過 31 個字元。
必須由字母數字字元(所有字母和數字 0 到 9)和下劃線 (_) 組成。
名稱的第一個字元必須是字母。
名稱不區分大小寫
關鍵字
關鍵字是為語言保留的特殊單詞。這些保留字不能用作識別符號或名稱。
下表列出了 Fortran 關鍵字:
非 I/O 相關的關鍵字 | ||||
---|---|---|---|---|
allocatable | allocate | assign | assignment | block data |
call | case | character | common | complex |
contains | continue | cycle | data | deallocate |
default | do | double precision | else | else if |
elsewhere | end block data | end do | end function | end if |
end interface | end module | end program | end select | end subroutine |
end type | end where | entry | equivalence | exit |
external | function | go to | if | implicit |
in | inout | integer | intent | interface |
intrinsic | kind | len | logical | module |
namelist | nullify | only | operator | optional |
out | parameter | pause | pointer | private |
program | public | real | recursive | result |
return | save | select case | stop | subroutine |
target | then | type | type() | use |
Where | While | |||
I/O 相關的關鍵字 | ||||
backspace | close | endfile | format | inquire |
open | read | rewind | Write |
廣告