Fortran 混合嵌套調(diào)用

2023-12-29 15:32 更新

一般地,子程序或者函數(shù)的參數(shù)都是一些來(lái)自主程序的局部變量,那么子程序中調(diào)用函數(shù)是否也需要在參數(shù)中進(jìn)行聲明呢?是的,子程序如果想要使用某個(gè)函數(shù),需要將函數(shù)名作為參數(shù)引用。

!!! 示例 10
subroutine subrout(subr, xmin, xmax, n)
implicit none
real xmin, xmax, dx, y
integer n, i
dx = (xmax - xmin)/n
do i = 0, n
call subr(dx*i+xmin, y)
print *, i, y
enddo
end subroutine subrout

subroutine funcout(fun, xmin, xmax, n)
implicit none
real fun, xmin, xmax, x, dx, y
integer n, i
dx = (xmax-xmin)/n
do i = 0, n
x = dx*i + xmin
y = func(x)**3
print *, x, y
enddo
end subroutine funcout

subroutine sub(x, y)
implicit none
real y, x
y = 2*sin(x) + cos(x**2)
end subroutine sub

function fun(x)
implicit none
real fun, x
fun = sin(x)**3
end function fun

program test_func
implicit none
real, external :: fun
external sub
call subrout(sub, 0.0, 3.0, 10)
call funcout(fun, 0.0, 3.0, 10)
end program test_func

!!! 執(zhí)行結(jié)果
>>> 0 1.00000000
1 1.58699322
2 2.06518173
3 2.25615215
4 1.99450183
5 1.36681640
6 0.952533364
7 1.42861772
8 2.21715832
9 1.38931477
10 -0.628890276
0.00000000 0.00000000
0.300000012 1.71903503E-05
0.600000024 5.83394058E-03
0.900000036 0.111042053
1.20000005 0.530770957
1.50000000 0.977679431
1.80000007 0.787805617
2.10000014 0.266100109
2.40000010 2.92694476E-02
2.70000005 4.75692534E-04
3.00000000 2.21971472E-08

上面的示例 10 是子程序和函數(shù)副程序的混合嵌套使用的一個(gè)范例,上述代碼的主要結(jié)構(gòu)如下所示:在主程序 test_func 中調(diào)用子程序 subrout 和 funcout,再由子程序 subrout 調(diào)用子程序 sub 以及子程序 funcout 調(diào)用函數(shù)副程序 fun。

test_func(主程序)
├── subrout(子程序)
│ └── sub(子程序)
└── funcout(子程序)
└── fun(函數(shù)副程序)

這里比較重要的是,在主程序中需要對(duì)遞歸調(diào)用的子程序和函數(shù)副程序進(jìn)行聲明。主程序中的遞歸子程序調(diào)用聲明只需要 external 加上子程序名即可,而主程序中的遞歸函數(shù)副程序調(diào)用聲明需要同時(shí)定義函數(shù)變量和函數(shù)名,因此寫為 real, external :: 加上函數(shù)副程序名。

當(dāng)然在直接調(diào)用函數(shù)副程序 fun 的子程序 funcout 中也需要定義函數(shù)同名變量,寫為 real fun。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)