Fortran - 运算符优先级



运算符优先级确定了表达式中术语的组合方式。这会影响表达式的评估方式。某些运算符比其他运算符具有更高的优先级;例如,乘法运算符比加法运算符具有更高的优先级。

例如 x = 7 + 3 * 2;这里,x 被赋值为 13,而不是 20,因为运算符 * 的优先级高于 +,所以它首先被 3*2 乘,然后加到 7 中。

这里,优先级最高的运算符出现在表格的顶部,优先级最低的运算符出现在底部。在表达式中,将首先评估优先级较高的运算符。

类别 运算符 结合性
逻辑非和负号 .not. (-) 从左到右
指数 ** 从左到右
乘法 * / 从左到右
加法 + - 从左到右
关系 < <= > >= 从左到右
相等 == /= 从左到右
逻辑与 .and. 从左到右
逻辑或 .or. 从左到右
赋值 = 从右到左

范例

尝试以下范例来理解 Fortran 中的运算符优先级 −

program precedenceOp
! this program checks logical operators

implicit none  

   ! variable declaration
   integer :: a, b, c, d, e
   
   ! assigning values 
   a = 20   
   b = 10
   c = 15
   d = 5
  
   e = (a + b) * c / d      ! ( 30 * 15 ) / 5
   print *, "Value of (a + b) * c / d is :    ",  e 

   e = ((a + b) * c) / d    ! (30 * 15 ) / 5
   print *, "Value of ((a + b) * c) / d is  : ",  e 

   e = (a + b) * (c / d);   ! (30) * (15/5)
   print *, "Value of (a + b) * (c / d) is  : ",  e 

   e = a + (b * c) / d;     !  20 + (150/5)
   print *, "Value of a + (b * c) / d is  :   " ,  e 
  
end program precedenceOp

当您编译并执行上述程序时,它会产生以下结果 −

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
fortran_operators.htm
广告
© . All rights reserved.