Fortran 变量
变量只不过是我们的程序可以操纵的存储区域的名称。每个变量都应该有一个特定的类型,这决定了变量内存的大小和布局;可以存储在该存储器内的值的范围;以及可以应用于变量的操作集。
变量的名称可以由字母、数字和下划线字符组成。Fortran 中的名称必须遵循以下规则:
- 它不能超过 31 个字符。
- 它必须由字母数字字符(字母表中的所有字母以及数字 0 到 9)和下划线 (_) 组成。
- 名字的第一个字符必须是字母。
- 名称不区分大小写。
| 序号 | 类型 & 描述 |
|---|---|
| 1 | 整型 它只能容纳整数值。 |
| 2 | 实数 它存储浮点数。 |
| 3 | 复数 它用于存储复数。 |
| 4 | 逻辑 它存储逻辑布尔值。 |
| 5 | 字符 它存储字符或字符串。 |
变量声明
变量在类型声明语句中的程序(或子程序)开头声明。
变量声明的语法如下:
type-specifier :: variable_name
实例如下:
integer :: totalreal :: averagecomplex :: cxlogical :: donecharacter(len = 80) :: message ! a string of 80 characters
稍后,您可以为这些变量赋值,例如:
total = 20000average = 1666.67done = .true.message = "A big Hello from Tutorials Point"cx = (3.0, 5.0) ! cx = 3.0 + 5.0i
您还可以使用内部函数 cmplx 为复杂变量赋值:
cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0icx = cmplx (x, y) ! cx = x + yi
以下实例演示了变量声明、赋值和在屏幕上的显示:
program variableTestingimplicit none! declaring variablesinteger :: totalreal :: averagecomplex :: cxlogical :: donecharacter(len=80) :: message ! a string of 80 characters!assigning valuestotal = 20000average = 1666.67done = .true.message = "A big Hello from Tutorials Point"cx = (3.0, 5.0) ! cx = 3.0 + 5.0iPrint *, totalPrint *, averagePrint *, cxPrint *, donePrint *, messageend program variableTesting
结果为:
200001666.67004(3.00000000, 5.00000000 )TA big Hello from Tutorials Point