错误:(1)处的符号不是虚拟变量。

huangapple go评论68阅读模式
英文:

Error: Symbol at (1) is not a DUMMY variable

问题

我尝试编写了一个计算两个数的最大公约数(GCD)的代码:

program main 
    implicit none
    integer::A,B,gcd,ans=0
    read*,A,B
    gcd = gcd(A,B)
    write(*,*) 'GCD of ',A,' and ',B,': ',gcd
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,但却得到了以下错误:

source_file.f:5:4:

     gcd(A,B)
    1
Error: Unclassifiable statement at (1)

我不明白为什么会出现这个错误。如果有人能解释我为什么会出现错误,我将不胜感激。

英文:

I tried to write a code which gives GCD of two number:

program main 
    implicit none
    integer::A,B,gcd,ans=0
    read*,A,B
    gcd(A,B)
    write(*,*)'GCD of ',A,' and ',B,': ',ans
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

My input was:

98 56

I expect 14 but got this error:

source_file.f:5:4:

     gcd(A,B)
    1
Error: Unclassifiable statement at (1)

I didn't understand why I am getting this error? I heartily thank if anyone explain me why am I getting error.

答案1

得分: 4

不能为结果变量指定intent(out)或任何其他意图或相关属性。请参阅https://stackoverflow.com/questions/27827878/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是一个与函数的结果变量无关的变量。即使名称相同,它们也是两个不同的东西。最好将它们中的一个重命名以使其清晰明了。

英文:

You cannot specify intent(out) or any other intent or related attribute for the result variable. See https://stackoverflow.com/questions/27827878/fortran-array-cannot-be-returned-in-function-not-a-dummy-variable

Use just

integer::ans

In addition, just

gcd(A,B)

is not a valid way to use a function in Fortran. Use

ans = gcd(A,B)

or

print *, gcd(A,B)

or similar.

Please realize that ans declared in the main program is a variable that is not related to the result variable of the function. Even if the name is the same, they are two different things. It will be better to rename one of them to make it clear.

huangapple
  • 本文由 发表于 2020年1月6日 20:29:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定