【问题标题】:Incorrect values from common block公共块中的值不正确
【发布时间】:2022-01-02 14:19:39
【问题描述】:

如何使用 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
    !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这是一个例子。 当我打印 f1(2.) 和 f2(3.) 时,第一个结果为真,第二个结果为假。

【问题讨论】:

    标签: fortran fortran-common-block


    【解决方案1】:

    您的帖子中有两个非常不同的问题。

    1. 我们如何在子程序之间共享数据?在现代 Fortran 中使用模块。我们对此有很多问题和答案。公共块已过时(自 Fortran 2018 起正式过时 - 感谢@steve)。

    2. 为什么使用common的结果不正确?

    您正在使用一个未命名的公共块。在普通块中,变量名称是无关紧要的。它们可以在编译单元(主程序、子程序)之间任意不同。顺序很重要。

    所以你的

    common d,e
    

    和做的一样

    common a,b
    

    要访问公共块的第五个元素,您必须拥有所有五个变量

    common a,b,c,d,e
    

    (或者正如 francescalus 指出的那样,必须引用正确的数字存储单元。Ome 也可以有一个数组。)

    最后,我想强调implicit none 的重要性。你真的应该使用它。

    【讨论】:

    • 谢谢!我明白了。非常感谢:)
    • 作为一个小问题,没有必要拥有“所有五个变量”,只需要有五个数字存储单元即可访问。
    • 从 Fortran 2018 开始,B.3 过时的特性:... (10) COMMON 和 EQUIVALENCE 语句,块数据程序单元见 B.3.11。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多