Fortran Coder

标题: 实例0831书中说不需要声明就可以用,但是出现报错 [打印本页]

作者: DDHH    时间: 2023-10-13 16:06
标题: 实例0831书中说不需要声明就可以用,但是出现报错
[Fortran] 纯文本查看 复制代码
program ex0831
implicit none
integer ::n
write(*,*)'N='
read (*,*)n
write(*,"(I2,'!=',I8)")n,fact(n)
stop
end

contains
recursive integer function fact(n)result(ans)
implicit none
integer ,intent(in)::n

if (n<0)then
ans=-1
return
else if (n<=1)then
ans =1
return
end if
ans=n*fact(n-1)
return
end function fact
end

--------------------Configuration: 21351 - Win32 Debug--------------------
Compiling Fortran...
E:\Fortran\MSDEV98\MyProjects\21351\320020.f90
E:\Fortran\MSDEV98\MyProjects\21351\320020.f90(6) : Error: This name does not have a type, and must have an explicit type.   [FACT]
write(*,"(I2,'!=',I8)")n,fact(n)
-------------------------^
Error executing df.exe.

21351.exe - 1 error(s), 0 warning(s)



作者: fcode    时间: 2023-10-13 17:27
去掉 stop 后面的 end

被主程序包含的 fact 函数需要放在program 里面,才能被 program 识别,实现不定义而使用。

此外,stop 其实也没有存在的必要。return 没必要存在
再次此外,当 fact 包含在 program 里面时,因为 program 中已经有 implicit none 了,所以 fact 函数里的 implicit none 也没必要存在。

[Fortran] 纯文本查看 复制代码
program ex0831
  implicit none
  integer ::n
  write(*,*)'N='
  read (*,*)n
  write(*,"(I2,'!=',I8)")n,fact(n)

contains

  recursive integer function fact(n) result(ans)
    integer ,intent(in)::n
    if (n<0)then
      ans=-1
    else if (n<=1)then
      ans =1
    else
      ans=n*fact(n-1)   
    end if
  end function fact
  
end program ex0831






欢迎光临 Fortran Coder (http://bbs.fcode.cn/) Powered by Discuz! X3.2