面试题答案
一键面试Fortran中模块(module)的作用
- 封装与组织代码:模块允许将相关的变量、子程序、函数等组合在一起,形成一个逻辑单元,提高代码的可读性和可维护性。
- 数据共享:模块中定义的变量可以在多个子程序或主程序间共享,避免了通过参数传递大量数据的繁琐。
- 作用域控制:模块提供了一种控制变量和子程序作用域的方式,只有在模块内部或明确使用该模块的程序单元中,才能访问模块中的内容,增强了代码的安全性和稳定性。
简单示例
! 定义模块
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
在上述示例中:
my_module
模块定义了一个全局变量global_variable
,并初始化其值为10。- 模块中包含两个子程序
print_variable
和update_variable
,分别用于打印变量值和更新变量值。 - 在主程序
main
中,通过use my_module
语句使用该模块,然后调用模块中的子程序来操作模块中定义的变量。