Fortran 常量
常量是指程序在执行过程中不能更改的固定值。这些固定值也称为字面量。
常量可以是任何基本数据类型,如整数常量、浮点常量、字符常量、复杂常量或字符串文字。只有两个逻辑常数:.true. 和 .false.
常量被视为常规变量,除了它们的值在定义后不能修改。
命名常量和文字
有两种类型的常数:
- 文字常量
- 命名常量
字面常量有值,但没有名称。
例如,以下是字面常量:
| 类型 | 实例 |
|---|---|
| 整型常量 | 0 1 -1 300 123456789 |
| 实数常量 | 0.0 1.0 -1.0 123.456 7.1E+10 -52.715E-30 |
| 复数常量 | (0.0, 0.0) (-123.456E+30, 987.654E-29) |
| 逻辑常量 | .true. .false. |
| Character constants | "PQR" "a" "123'abc$%#@!" " a quote "" " 'PQR' 'a' '123"abc$%#@!' ' an apostrophe '' ' |
命名常量有一个值和一个名称。
命名常量应在程序或过程的开头声明,就像变量类型声明一样,指示其名称和类型。命名常量用参数属性声明。例如,
real, parameter :: pi = 3.1415927
实例
以下程序计算重力作用下垂直运动引起的位移。
program gravitationalDisp! this program calculates vertical motion under gravityimplicit none! gravitational accelerationreal, parameter :: g = 9.81! variable declarationreal :: s ! displacementreal :: t ! timereal :: u ! initial speed! assigning valuest = 5.0u = 50! displacements = u * t - g * (t**2) / 2! outputprint *, "Time = ", tprint *, 'Displacement = ',send program gravitationalDisp
结果为:
Time = 5.00000000Displacement = 127.374992