計算機程式Computer Programming Language
Lecture 2 Introduction to Fortran
郭修伯 助理教授 ( 5488 )
Fixed Format
• Fortran 77 (*.f /*.for)– 欄位: 1
• C 為註解– 欄位: 1-5
• 為行號– 欄位: 6
• 為序接欄位– 欄位: 7-72
• 為程式區
Free Format
• Fortran 90/95 (*.f90)– ! 之後為註解– 一行有 132 字元– 行號在最前面– & 為連接上一行
A simple program:print a line of text• Fortran 90
A simple program:print a line of text• Fortran 77
A simple program: add two integers• Fortran 90
A simple program: add two integers• Fortran 77
Important issues
• 程式前要寫 Comments
• Fortran 77 用單引號 ; Fortran 90 用雙引號• Fortran programs contain one or more
functions, exactly one of which must be main
• stop and end
• 數學運算式 +, -, *, / ,**, ( )
簡單的程式結構program main
implicit noneinteger a,b,c
b=1c=2a=b+cwrite (*,*) a
stopend
宣告• 向電腦要求一塊記錄的記憶體空間
– 用大小寫英文字母、 1 到 9 的數字和下橫線;第一個字母必須是字母或數字
– 變數名稱長度• 77 - 6 字元• 90 - 31 字元
– 大小寫字母意義相同– 不可用 Fortran 的關鍵字
• Integer; Real; Complex; Character; Logical
Integer
• 短整數 (2 bytes) -32768 ~ 32768– Integer*2 a (Fortran 77)
– Integer (kind=2) a (Fortran 90)
• 長整數 (4 bytes) -2147483648 ~ 2147483648– Integer a (Fortran 77 & 90)
– Interger:: a (Fortran 90)
– Integer*4 a (Fortran 77)
– Integer (kind=4) a (Fortran 90)
型態宣告的重要性
Real
• 單精準度浮點數 (4 bytes) -3.4e38 ~ 3.4e38– Real a (Fortran 77 & 90)
– Real:: a (Fortran 90)
– Real*4 a (Fortran 77)
– Real (kind=4) a (Fortran 90)
• 雙精準度浮點數 (8 bytes) -1.79e308 ~ 1.79e308– Double precision a (Fortran 77 & 90)
– Real*8 a (Fortran 77)
– Real (kind=8) a (Fortran 90)
Complex
• 單精準度複數 (4 bytes) -3.4e38 ~ 3.4e38– Complex a (Fortran 77 & 90)
– Complex:: a (Fortran 90)
– Complex*4 a (Fortran 77)
– Complex (kind=4) a (Fortran 90)
• 雙精準度複數 (8 bytes) -1.79e308 ~ 1.79e308– Complex*8 a (Fortran 77)
– Complex (kind=8) a (Fortran 90)
Character• 字串 ( ? 字元 )
– Character*20 a (Fortran 77)
– Character(len=20) a (Fortran 90)
Logical• 邏輯變數
– Logical a
READ 輸入資料• read (*,*) a
• read (5,*) a
• read (5,100) a
• read (unit = 5, fmt = 100) a
More about Format
• Refer to textbook 4-4– A10– F9.3– I5– G9.3– /– 3X
Implicit
• Implicit none• 取消內定型態 ; 緊接在 Program 之後
Parameter 設立常數值• parameter (pi = 3.14159)
• Pi = 3.14159; G = 9.81; R = 8.314 … etc.
• 避免錯誤• 增加程式速度
設定初始值
型態不同變數運算
Type• integer, real, logical, character 之外的型態宣告