Fortran - 如果 - 那麼 - 別的構造



如果…那麼語句後可以接一個可選的else 語句,當邏輯表示式為假時執行此語句。

語法

>

如果…那麼…else 語句的基本語法是 -

if (logical expression) then      
   statement(s)  
else
   other_statement(s)
end if

但是,如果您給if 塊命名,那麼命名的if-else 語句的語法將如下所示 -

[name:] if (logical expression) then      
   ! various statements           
   . . . 
   else
   !other statement(s)
   . . . 
end if [name]

如果邏輯表示式求值為true,那麼if…then 語句中的程式碼塊將被執行,否則else 塊中的程式碼塊將被執行。

流程圖

Flow Diagram1

示例

program ifElseProg
implicit none
   ! local variable declaration
   integer :: a = 100
 
   ! 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"
   else
   print*, "a is not less than 20"
   end if
       
   print*, "value of a is ", a
	
end program ifElseProg

編譯並執行以上程式碼時,會產生以下結果 -

a is not less than 20
value of a is 100
fortran_decisions.htm
廣告
© . All rights reserved.