0 fortran fortran-common-block
如何使用 Fortran 创建例程和子程序之间的链接?
Program Example
common a,b,c,d,e
print*,"Enter a"
read*,a
print*,"Enter coefficient of x in f1(x)"
read*,b
print*,"Enter intercept in f1(x)"
read*,c
print*,"Enter coefficient of x in f2(x)"
read*,d
print*,"Enter intercept in f2(x)"
read*,e
Print*,f1(2.),f2(3.)
pause
end
!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function f1(x)
common a,b,c
f1=a*x**2+b*x+c
return
end
!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function f2(y)
common d,e
f2=d*y+e
return
end
!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
这是一个例子。当我打印 f1(2.) 和 f2(3.) 时,第一个结果为 true,第二个结果为 false。
您的帖子中有两个截然不同的问题。
我们如何在子程序之间共享数据?在现代 Fortran 中使用模块。对此我们有很多问题和答案。通用块已过时(自 Fortran 2018 起正式过时 - 感谢 @steve)。
为什么使用结果common不正确?
You are using an unnamed common block. In comon blocks the variable names are irrelevant. They can differ arbitrarily between compilation units (main program, subprograms). The order is important.
Therefore your
common d,e
Run Code Online (Sandbox Code Playgroud)
is the same as doing
common a,b
Run Code Online (Sandbox Code Playgroud)
To get access to the fifth element of the common block you must have all five variables
common a,b,c,d,e
Run Code Online (Sandbox Code Playgroud)
(or as francescalus points out, one has to reference the right numerical storage unit. Ome could also have one array instead.)
Finally, I would like the stress the importance of implicit none. You should really use it.