错误:(1)处的符号不是DUMMY变量

问题描述 投票:0回答:1

我试图编写一个代码,使GCD为两个数字:

program main 
    implicit none
    integer::A,B,gcd,ans
    read*,A,B
    write(*,*)'GCD of ',A,' and ',B,': ',gcd(A,B)
end program main

recursive function gcd(A,B) result(ans)
    implicit none 
    integer,intent(in)::A,B
    integer::ans
    if (A==0) ans=B
    if (B==0) ans=A
!base_case
    if (A==B) ans=A
!recursive_case
    if (A>B)then
        ans=gcd(A-B,B)
    else 
        ans=gcd(A,B-A)
    end if 
end function gcd

我的输入是:

98 56

我希望14,但出现此错误:

Invalid memory reference (SIGSEGV)

我不明白为什么会收到此错误?我衷心感谢任何人向我解释为什么我会出错。

recursion fortran
1个回答
0
投票

您不能为结果变量指定intent(out)或任何其他意图或相关属性。参见Fortran array cannot be returned in function: not a DUMMY variable

仅使用

integer::ans

另外,只是

gcd(A,B)

不是在Fortran中使用函数的有效方法。使用

ans = gcd(A,B)

print *, gcd(A,B)

或类似。

请注意,在主程序中声明的ans是与该函数的结果变量无关的变量。即使名称相同,它们也是两个不同的事物。最好重命名其中之一以使其清楚。

© www.soinside.com 2019 - 2024. All rights reserved.