fortran模块与函数

fortran模块与函数

模块(module)用于将相关的变量、类型、子程序、函数等打包在一起,实现代码复用与命名空间管理。函数(function)与子程序类似,但它必须返回一个值。示例代码如下:

module math_mod             ! 定义名为 math_mod 的模块
  implicit none
contains
  function add(x, y) result(res)
    integer, intent(in) :: x, y  ! 输入参数
    integer :: res                ! 返回值变量
    res = x + y                   ! 计算并赋值给 res
  end function add

  subroutine greet(name)
    character(len=*), intent(in) :: name  ! 输入参数 name
    print *, 'Hello, ', trim(name), ' from Fortran!'
  end subroutine greet
end module math_mod

program test_math_mod
  use math_mod               ! 导入 math_mod 模块
  implicit none
  integer :: a, b, sum
  character(len=20) :: who
  a = 10
  b = 25
  sum = add(a, b)            ! 调用函数 add,求和
  print *, '10 + 25 =', sum
  print *, '请输入两个整数:'
  read(*, *) a, b            ! 从标准输入读取 a 和 b
  sum = add(a, b)
  print *, '输入的两数之和是:', sum
  who = 'hong'
  call greet(who)            ! 调用子程序 greet
  call greet('Fortran')      ! 直接传递字符常量
end program test_math_mod
  • module math_mod / end module math_mod:模块定义的开始与结束。
  • contains:模块内部函数、子程序开始标志。
  • use math_mod:在主程序或其他模块中导入模块中的公共实体。
  • 函数 add 使用 result(res) 指定返回值,返回类型为 integer;子程序 greet 用于打印问候。