Fortran 简明教程
Fortran - Basic Syntax
Fortran 程序由各种程序单元组成,例如主程序、模块以及外部子程序或过程。
每个程序包含一个主程序,而且可以或不可以包含其他程序单元。主程序的语法如下所示 −
program program_name
implicit none
! type declaration statements
! executable statements
end program program_name
A Simple Program in Fortran
让我们编写一个可以添加两个数字,并打印结果的程序 −
program addNumbers
! This simple program adds two numbers
implicit none
! Type declarations
real :: a, b, result
! Executable statements
a = 12.0
b = 15.0
result = a + b
print *, 'The total is ', result
end program addNumbers
当您编译和执行上述程序时,它将生成以下结果 −
The total is 27.0000000
请注意 −
-
所有 Fortran 程序都以关键字 program 开头,以关键字 end program, 结尾,后跟程序的名称。
-
implicit none 语句允许编译器检查所有变量类型是否已正确声明。您必须始终在每个程序的开头使用 implicit none 。
-
Fortran 中的注释以感叹号 (!) 开始,因为此号 (在字符字符串中除外) 后的所有字符都会被编译器忽略。
-
print * 命令可在屏幕上显示数据。
-
缩进代码行有利于保持程序的可读性。
-
Fortran 同时允许使用大写字母和小写字母。Fortran 不区分大小写,但字符串文字除外。
Basics
Fortran 的 basic character set 包含 −
-
字母 A … Z 和 a … z
-
数字 0 … 9
-
the underscore (_) character
-
特殊字符 = : + 空格 - * / ( ) [ ] , . $ ' ! " % & ; < > ?
Tokens 由基本字符集中的字符组成。标记可以是关键字、标识符、常量、字符串文字或符号。
程序语句由标记组成。
Identifier
标识符是用来标识变量、过程或任何其他用户定义项的名称。Fortran 中的名称必须遵循以下规则 −
-
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
Keywords
Keywords are special words, reserved for the language. These reserved words cannot be used as identifiers or names.
The following table, lists the Fortran keywords −
The non-I/O keywords |
allocatable |
allocate |
assign |
assignment |
block data |
call |
case |
character |
common |
complex |
contains |
continue |
cycle |
data |
deallocate |
default |
do |
double precision |
else |
else if |
elsewhere |
end block data |
end do |
end function |
end if |
end interface |
end module |
end program |
end select |
end subroutine |
end type |
end where |
entry |
equivalence |
exit |
external |
function |
go to |
if |
implicit |
in |
inout |
integer |
intent |
interface |
intrinsic |
kind |
len |
logical |
module |
namelist |
nullify |
only |
operator |
optional |
out |
parameter |
pause |
pointer |
private |
program |
public |
real |
recursive |
result |
return |
save |
select case |
stop |
subroutine |
target |
then |
type |
type() |
use |
Where |
While |
The I/O related keywords |
backspace |
close |
endfile |
format |
inquire |
open |
read |
rewind |
Write |