Fortran Coder

标题: 子例行程序 [打印本页]

作者: 胆怯滴大侠    时间: 2021-4-18 15:14
标题: 子例行程序
本帖最后由 胆怯滴大侠 于 2021-4-18 15:19 编辑

[Fortran] 纯文本查看 复制代码

program hello
    implicit none
    integer n,s

    subroutine fcount(n,s)
    s=0
    do i=1,n
        s=s+1./i
    end do
    end

    call fcount(50,s1)
    call fcount(100,s2)
    call fcount(150,s3)
    call fcount(200,s4)
    s=s1+s2+s3+s4
    print *, "s=", s

end program



求助,请教大佬们,subroutine fcount(n,s)这里报错了,这个问题怎么解决呢?

屏幕截图 2021-04-18 151612.png (3.15 KB, 下载次数: 313)

屏幕截图 2021-04-18 151612.png

作者: vvt    时间: 2021-4-18 16:19
程序单元里不能直接放入另一个程序单元,需要符合一定的规则。

[Fortran] 纯文本查看 复制代码
program hello
  implicit none
  real :: ss,s(4)

  call fcount(50,s(1))
  call fcount(100,s(2))
  call fcount(150,s(3))
  call fcount(200,s(4))
  ss=sum(s)
  print *, "s=", ss

contains

subroutine fcount(n,s)
  integer :: n , i
  real :: s
  s=0
  do i=1,n
    s=s+1./i
  end do
end subroutine fcount

end program hello

作者: 胆怯滴大侠    时间: 2021-4-18 16:30
vvt 发表于 2021-4-18 16:19
程序单元里不能直接放入另一个程序单元,需要符合一定的规则。

[mw_shl_code=fortran,true]program hello

非常感谢
作者: vvt    时间: 2021-4-18 16:32
考虑到 Fortran 是一门向量化的语言,给出一个高级的版本,非常简单且高效。

[Fortran] 纯文本查看 复制代码
program hello
  implicit none
  write(*,*) "s=", sum(fcount([50,100,150,200]))

contains

Elemental Real Function fcount(n) result( s )
  integer , intent(IN) :: n
  integer :: i
  s=sum(1./[(i,i=1,n)])
End Function fcount

End program hello





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