fortran fortran中文资料网
手气不错
Article

019.unraySign_一元运算符

2026年6月16日入门级


一元正负号是写在单个数值或变量前面的符号,表示该量的正负方向。例如物理中速度、位移、力、电荷量、温度变化等都可能带有正负号,用来表达方向、增减或相对关系。可以表示沿正方向的力、反方向的位移、正电荷与负电荷、温度升高与降低、收入与支出等。

不同于二元加减号,二元加减号连接两个量,表示两个量之间的加法或减法关系;一元正负号只修饰一个量,表示这个量本身的符号。

本文代码

program unarySignDemo
  implicit none
  real :: forceNewton ! 单位N
  real :: positiveForce ! 一元正号
  real :: negativeForce ! 一元负号
  real :: sumForce ! 二元加号
  real :: differenceForce ! 二元减号
  real :: powerWithoutParentheses ! 无括号
  real :: powerWithParentheses ! 有括号
  forceNewton=5.0
  positiveForce=+forceNewton
  negativeForce=-forceNewton
  sumForce=forceNewton+2.0
  differenceForce=forceNewton-2.0
  powerWithoutParentheses=-2.0**2
  powerWithParentheses=(-2.0)**2
  print "(A)","一元正负号:"
  print "(A,F8.4)","一元正号+forceNewton=",positiveForce
  print "(A,F8.4)","一元负号-forceNewton=",negativeForce
  print "(A,F8.4)","二元加号forceNewton+2.0=",sumForce
  print "(A,F8.4)","二元减号forceNewton-2.0=",differenceForce
  print "(A,F8.4)","未加括号的-2.0**2=",powerWithoutParentheses
  print "(A,F8.4)","加括号的(-2.0)**2=",powerWithParentheses
end program unarySignDemo

编译运行

(base) hong@hongdeMacBook-Pro 019.unarySign % gfortran exampleUnarySign.f90 
(base) hong@hongdeMacBook-Pro 019.unarySign % ./a.out 
一元正负号:
一元正号+forceNewton=  5.0000
一元负号-forceNewton= -5.0000
二元加号forceNewton+2.0=  7.0000
二元减号forceNewton-2.0=  3.0000
未加括号的-2.0**2= -4.0000
加括号的(-2.0)**2=  4.0000
(base) hong@hongdeMacBook-Pro 019.unarySign % 

结果分析

  • 一元正号:+forceNewton= 5.0000 正5=5
  • 一元负号:-forceNewton= -5.0000 负5=-5
  • 二元加号:forceNewton+2.0= 7.0000 5+2
  • 二元减号:forceNewton-2.0= 3.0000 5-2
  • 一元无括号:-2.0^2= -4.0000 对2^2取反
  • 一元有括号:(-2.0)^2= 4.0000 负2的平方

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注