MST

星途 面试题库

面试题:Fortran中模块的使用

请阐述Fortran中模块(module)的作用,并且编写一个简单示例,展示如何在模块中定义变量、子程序,并在主程序中调用这些内容。
12.2万 热度难度
编程语言Fortran

知识考点

AI 面试

面试题答案

一键面试

Fortran中模块(module)的作用

  1. 封装与组织代码:模块允许将相关的变量、子程序、函数等组合在一起,形成一个逻辑单元,提高代码的可读性和可维护性。
  2. 数据共享:模块中定义的变量可以在多个子程序或主程序间共享,避免了通过参数传递大量数据的繁琐。
  3. 作用域控制:模块提供了一种控制变量和子程序作用域的方式,只有在模块内部或明确使用该模块的程序单元中,才能访问模块中的内容,增强了代码的安全性和稳定性。

简单示例

! 定义模块
module my_module
    implicit none
    ! 在模块中定义变量
    integer :: global_variable = 10

    contains
        ! 在模块中定义子程序
        subroutine print_variable()
            print *, 'The value of global_variable is:', global_variable
        end subroutine print_variable

        subroutine update_variable(new_value)
            integer, intent(in) :: new_value
            global_variable = new_value
        end subroutine update_variable
end module my_module

! 主程序
program main
    use my_module
    implicit none

    call print_variable()
    call update_variable(20)
    call print_variable()

end program main

在上述示例中:

  1. my_module模块定义了一个全局变量global_variable,并初始化其值为10。
  2. 模块中包含两个子程序print_variableupdate_variable,分别用于打印变量值和更新变量值。
  3. 在主程序main中,通过use my_module语句使用该模块,然后调用模块中的子程序来操作模块中定义的变量。