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 print read rewind Write
廣告