包含 fortran 子程序和函数的模块

Modules containing subroutines and functions in fortran

我正在学习正确使用子程序、函数和模块,下面是一个简单的例子,编译时没有出错,执行后结果是4.57187637E-41而不是pi,我有查了好几篇,还没发现错误。

module wz
   implicit none
   private
   public :: print_out
   real,parameter :: pi = 3.14159
   contains
      subroutine print_out
      implicit none
      real :: area
      print *, area
      end subroutine print_out

      function f(x) result(area)
      implicit none

      real, intent(in):: x
      real            :: area

      area = pi * x ** 2
      end function f
end module wz

program test_module
use wz
implicit none
    real :: x
    x = 1.
   call print_out
end program test_module

您正在打印的值是 area 就在声明之后和对其进行任何操作之前。您需要将 x 传递给 f 函数,您可以通过 print_out 子例程来实现:

module wz
   implicit none
   private
   public :: print_out
   real,parameter :: pi = 3.14159
   contains
      subroutine print_out(x)
      implicit none
      real, intent(in) :: x
      real :: area
      area = f(x)
      print *, area
      end subroutine print_out

      function f(x) result(area)
      implicit none

      real, intent(in):: x
      real            :: area

      area = pi * x ** 2
      end function f
end module wz

program test_module
use wz
implicit none
    real :: x
    x = 1.
   call print_out(x)
end program test_module