Fortran 简明教程
Fortran - Constants
常量是指程序在其执行期间不能更改的固定值。这些固定值也称为 literals 。
The constants refer to the fixed values that the program cannot alter during its execution. These fixed values are also called literals.
常量可以是任意基本数据类型,例如整型常量、浮点常量、字符常量、复常量或字符串常量。只有两个逻辑常量: .true. 和 .false.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a complex constant, or a string literal. There are only two logical constants : .true. and .false.
常量与常规变量一样,不同之处在于它们的的值在定义后不能修改。
The constants are treated just like regular variables, except that their values cannot be modified after their definition.
Named Constants and Literals
有两种类型的常量:
There are two types of constants −
-
Literal constants
-
Named constants
字面常量有一个值,但没有名称。
A literal constant have a value, but no name.
例如,以下是字面常量 -
For example, following are the literal constants −
Type |
Example |
Integer constants |
0 1 -1 300 123456789 |
Real constants |
0.0 1.0 -1.0 123.456 7.1E+10 -52.715E-30 |
Complex constants |
(0.0, 0.0) (-123.456E+30, 987.654E-29) |
Logical constants |
.true. .false. |
Character constants |
"PQR" "a" "123’abc$%@!" " a quote "" " 'PQR' 'a' '123"abc$%@!' ' an apostrophe '' ' |
已命名常量既有值又有名称。
A named constant has a value as well as a name.
已命名常量应在程序或过程的开头声明,如同变量类型声明,指示其名称和类型。已命名常量用参数属性声明。例如,
Named constants should be declared at the beginning of a program or procedure, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example,
real, parameter :: pi = 3.1415927
Example
以下程序计算重力作用下垂直运动的位移。
The following program calculates the displacement due to vertical motion under gravity.
program gravitationalDisp
! this program calculates vertical motion under gravity
implicit none
! gravitational acceleration
real, parameter :: g = 9.81
! variable declaration
real :: s ! displacement
real :: t ! time
real :: u ! initial speed
! assigning values
t = 5.0
u = 50
! displacement
s = u * t - g * (t**2) / 2
! output
print *, "Time = ", t
print *, 'Displacement = ',s
end program gravitationalDisp
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Time = 5.00000000
Displacement = 127.374992