Fortran 简明教程
Fortran - Variables
变量只不过是一个存储区域的名称,我们的程序可以对其进行操作。每个变量应该有特定的类型,它确定变量内存的大小和布局;可以在该内存内存储的值范围;以及可以应用于该变量的操作集。
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable should have a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
变量的名称可以由字母、数字和下划线字符组成。Fortran 中的名称必须遵循以下规则:
The name of a variable can be composed of letters, digits, and the underscore character. A name in Fortran must follow the following rules −
-
It cannot be longer than 31 characters.
-
It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_).
-
First character of a name must be a letter.
-
Names are case-insensitive.
根据前一章中解释的基本类型,以下是有类型变量:
Based on the basic types explained in previous chapter, following are the variable types −
Sr.No |
Type & Description |
1 |
Integer It can hold only integer values. |
2 |
Real It stores the floating point numbers. |
3 |
Complex It is used for storing complex numbers. |
4 |
Logical It stores logical Boolean values. |
5 |
Character It stores characters or strings. |
Variable Declaration
变量在程序(或子程序)开始时在类型声明语句中进行声明。
Variables are declared at the beginning of a program (or subprogram) in a type declaration statement.
变量声明的语法如下:
Syntax for variable declaration is as follows −
type-specifier :: variable_name
For example
integer :: total
real :: average
complex :: cx
logical :: done
character(len = 80) :: message ! a string of 80 characters
稍后,您可以将值赋给这些变量,例如:
Later you can assign values to these variables, like,
total = 20000
average = 1666.67
done = .true.
message = “A big Hello from Tutorials Point”
cx = (3.0, 5.0) ! cx = 3.0 + 5.0i
您还可以使用内在函数 cmplx, 将值赋给复变量:
You can also use the intrinsic function cmplx, to assign values to a complex variable −
cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0i
cx = cmplx (x, y) ! cx = x + yi
Example
以下示例演示变量声明、赋值和屏幕显示:
The following example demonstrates variable declaration, assignment and display on screen −
program variableTesting
implicit none
! declaring variables
integer :: total
real :: average
complex :: cx
logical :: done
character(len=80) :: message ! a string of 80 characters
!assigning values
total = 20000
average = 1666.67
done = .true.
message = "A big Hello from Tutorials Point"
cx = (3.0, 5.0) ! cx = 3.0 + 5.0i
Print *, total
Print *, average
Print *, cx
Print *, done
Print *, message
end program variableTesting
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
20000
1666.67004
(3.00000000, 5.00000000 )
T
A big Hello from Tutorials Point