Fortran if...then語句結構

if ... then 語句由一個邏輯運算式後跟一個或多個語句和終止 end if 語句。

語法

if… then 語句的基本語法:

if (logical expression) then
   statement
end if

但是可以給一個名稱,if 塊,那麼語法命名 if 語句如下:

[name:] if (logical expression) then
   ! various statements
   . . .
end if [name]

如果邏輯運算式的計算結果為true,那麼塊代碼內的 if ... then 語句會被執行。如果在結束後的邏輯運算式計算為false,那麼第一個代碼塊之後的 if 語句會被執行。

流程圖:

Flow Diagram

示例 1

program ifProg
implicit none
   ! local variable declaration
   integer :: a = 10

   ! check the logical condition using if statement
   if (a < 20 ) then

   !if condition is true then print the following
   print*, "a is less than 20"
   end if

   print*, "value of a is ", a
 end program ifProg

當上述代碼被編譯和執行時,它產生了以下結果:

a is less than 20
value of a is 10

示例 2

這個例子說明了命名的 if 塊:

program markGradeA
implicit none
   real :: marks
   ! assign marks
   marks = 90.4
   ! use an if statement to give grade

   gr: if (marks > 90.0) then
   print *, " Grade A"
   end if gr
end program markGradeA   

當上述代碼被編譯和執行時,它產生了以下結果:

Grade A

上一篇: Fortran選擇決策 下一篇: Fortran if...then...else 結構