【问题标题】:How to return a value from subroutine如何从子程序返回值
【发布时间】:2026-02-01 18:50:01
【问题描述】:

我不想使用全局值,这对于大型程序很危险。代码是这样的

subroutine has_key(id)
  if (true) then 
     return 1
  else
     return 0
  end if
end subroutine

subroutine main
   if(has_key(id))
      write(*,*) 'it works!'
end subroutine

我怎样才能使用子程序做这样的事情。我正在考虑返回一个标志,但我可能会使用一个全局值。有人知道吗?

【问题讨论】:

    标签: return-value fortran90 subroutine


    【解决方案1】:

    像这样

    subroutine test(input, flag)
       integer, intent(in) :: input
       logical, intent(out) :: flag
       flag = input>=0
    end subroutine
    

    call test(3,myflag)
    

    将 myflag 设置为 .true.

    注意

    • 子例程通过其参数列表返回值;
    • 使用intent 子句告诉编译器子例程可以对其参数做什么;
    • 我的示例非常简单,您可能希望根据自己的需要对其进行调整。

    【讨论】:

      【解决方案2】:

      你也可以用一个函数来做。假设它对偶数返回 true

      logical function has_key(id)
         integer, intent(in):: id
         has_key = mod(id,2) .eq. 0
      end function has_key
      
      program main
         do ii = 1, 4
            if(has_key(ii))
               print *, ii, ' has key'
            else
               print *, ii, ' no key'
            end if
         end do
      end program
      

      【讨论】:

      • 感谢您的回答!但由于某种原因我必须使用子程序,因为没有程序,我尝试将它与其他编程语言耦合。