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程式start關鍵字程式和end關鍵字結束程式,然後是該程式的名稱。

  • 隱無語句允許編譯器檢查所有的變數類型是正確聲明。必須始終使用無隱在每個程式的開始。

  • 在Fortran語言注釋開始使用感嘆號(!),因為在這之後的所有字元(除字串)被編譯器忽略。

  • print*命令在螢幕上顯示數據。

  • 代碼行縮進,是保持一個程式讀取一個很好的做法。

  • Fortran語言允許大寫和小寫字母。 Fortran語言是區分大小寫的,除了字串常量。

基礎知識

Fortran語言的基本字元集包括:

  • 字元包括 A ... Z 和 a ... z
  • 數字 0 ... 9
  • 下劃線(_)字元
  • 特殊字元 = : + 空格- * / ( ) [ ] , . $ ' ! " % & ; < > ?

令牌Tokens基本字元集中的字元。令牌可以是一個關鍵字,識別字,常量,字串文字或符號。

程式語句作出標記。

識別字

一個識別字是用於標識一個變數,過程或任何其他用戶定義的專案的名稱。在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


上一篇: Fortran語言環境設置 下一篇: Fortran數據類型