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, 那麼 end 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_decisions.htm
廣告
© . All rights reserved.