Fortran 简明教程

Fortran - Variables

变量只不过是一个存储区域的名称,我们的程序可以对其进行操作。每个变量应该有特定的类型,它确定变量内存的大小和布局;可以在该内存内存储的值范围;以及可以应用于该变量的操作集。

变量的名称可以由字母、数字和下划线字符组成。Fortran 中的名称必须遵循以下规则:

  1. It cannot be longer than 31 characters.

  2. It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_).

  3. First character of a name must be a letter.

  4. Names are case-insensitive.

根据前一章中解释的基本类型,以下是有类型变量:

Sr.No

Type & Description

1

Integer 它只能存储整数。

2

Real 它存储浮点数。

3

Complex 它用于存储复数。

4

Logical 它存储逻辑布尔值。

5

Character 它存储字符或字符串。

Variable Declaration

变量在程序(或子程序)开始时在类型声明语句中进行声明。

变量声明的语法如下:

type-specifier :: variable_name

For example

integer :: total
real :: average
complex :: cx
logical :: done
character(len = 80) :: message ! a string of 80 characters

稍后,您可以将值赋给这些变量,例如:

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, 将值赋给复变量:

cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0i
cx = cmplx (x, y) ! cx = x + yi

Example

以下示例演示变量声明、赋值和屏幕显示:

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

编译并执行上述代码后,将产生以下结果 −

20000
1666.67004
(3.00000000, 5.00000000 )
T
A big Hello from Tutorials Point