一、子程序
写程序时候,可以把一段经常使用的、具有特定功能的程序代码独立处理爱,封装成子程序,以后只需要使用call调用就可以执行这一程序
Program example
== ==
call message
call add(a,b)
end
subroutine message()
write(*,*)"Hello"
return
end
subroutine add(first,second)
implicit none
integer::first,second
write(*,*)first+second
return
end
二、自定义函数
自定义程序的也需要调用才能执行,也可以独立声明,但是和子程序有两点不同。
①调用自定义函数前需要声明
②自定义函数会返回一个数值
Program example
implicit none
integer::a=2,b=3
integer,external::add
!调用函数add,不需要使用call命令
end
function add(first,second)
implicit none
integer::first,second
integer::add
add=first+second
return
end
调用函数add,不需要使用call命令
也可以简单定义函数,此时无需调用。
Program example
implicit none
real::a=1
real::b
real::add
add(a,b)=a+b
write(*,*)add(a,3.0)
end
三、全局变量
1、全局变量定义
Program example
integer::a,b,c,d,f
common a,b,c,d,f
a=1
b=2
call show()
write(*,*)a,b
end
subroutine show()
implicit none
integer::num1,num2,num3,num4,num5,num6
common num1,num2,num3,num4,num5,num6
num1=5
return
end
2、设置变量组
Program example
integer::a,b,c,d,e,f
common /group1/a,b,c
common /group2/d,e,f
data a,b,c/1,2,3/
data d,e,f/4,5,6/
call show()
write(*,*)a,b
end
subroutine show()
implicit none
integer::num1,num2,num3,num4,num5,num6
common /group1/num1,num2,num3
common /group2/num4,num5,num6
num1=34
num2=25
return
end
3、变量的生命周期
通常子程序/函数使用结束后,其变量也会随着程序而消除。使用save命令可以使局部变量的生命周期延长直到整个程序结束。
子程序中:
integer::i
save i
四、函数参数的传递
1、参数传递
func(num,f)
!参数可以是任何数据类型,也可以是函数
real,intrinsic::sin !声明sin是库函数
2、参数的只读 intent
在Fortran中,子程序内部变量可以影响局部变量的,可以用intent声明参数只是可读的
格式:①integer,intent(in)::a
指定a只读,不能改变值
②integer,intent(out)::b
指定b在子程序中应该重新赋值
③integer,intent (inout)::c
指定c可读可写
3、函数的使用接口
interface是一段程序模块,用来说明所需调用函数的参数类型以及返回值类型等。
使用函数在以下情况是有必要说明使用接口的
①函数返回值为数组时候
②指定参数位置用来传递参数
③所调用的函数参数数目不固定时候
④输入指标参数时候
⑤函数返回值为指针时候
4、不定个数的参数程序
格式:integer,optinal::b
在调用函数时候,则该参数可以省略
5、改变参数传递位置
subroutine sub(a,b,c)
call sub(b=2,a=1,c=3)
6、函数递归
!Fortran 实现递归需要添加声明
格式:
recursive integer function fact(n) result(ans)
fact是函数名
ans是返回值
在Fortran的递归中, 输入和输出是分开的
7、内部函数
把函数定义在另一个函数内部
理解为函数的嵌套
在定义前用contains命令进行声明
在下一行开始定义内部函数
!只能被包含它的函数、子程序、主程序调用
8、module命令
用于特定程序模块的封装
把全局变量声明在module中,使用时仅需use module
格式:
module name
...
end
9、函数的重载
在Fortran中,函数重载需要再module中使用interface
可以用来定义一个虚拟函数名称
!将多个子程序重命名为1个,调用时候根据传入参数类型以此决定使用哪个函数
10enry
在函数中定义一个进入口,调用该进入口,则程序会从该入口处开始执行,而跳过在该点之前的代码。
---慎用
11、自定义操作符