以下代码展示了如何在Fortran中定义一个简单的数学模块,并在主程序中使用这个模块。
fortran
复制代码
module math_operations
implicit none
! 定义模块中的公共数据和子程序
real :: pi = 3.14159
contains
! 计算圆的面积
real function circle_area(radius)
real, intent(in) :: radius
circle_area = pi * radius**2
end function circle_area
end module math_operations
program use_math_module
use math_operations
implicit none
real :: r = 2.0
real :: area
! 使用模块中的子程序计算圆的面积
area = circle_area(r)
! 打印结果
print *, 'Radius = ', r
print *, 'Area = ', area
end program use_math_module
代码解释
模块定义: 使用 module 关键字定义了一个名为 math_operations 的模块,其中包含了公共变量 pi 和子程序 circle_area。模块使用: 使用 use 语句将 math_operations 模块引入到主程序 use_math_module 中,从而可以访问模块中定义的数据和子程序。子程序调用: 在主程序中调用 circle_area 子程序来计算圆的面积。打印结果: 使用 print 语句打印计算得到的圆的半径和面积。编译和运行
要编译并运行上述代码,可以使用如下命令:
bash
复制代码
gfortran math_operations.f90 use_math_module.f90 -o use_math_module
./use_math_module
示例2: 模块化程序结构
使用多个模块构建程序
以下代码展示了如何在Fortran中使用多个模块来构建一个更复杂的程序结构。
fortran
复制代码
module constants
implicit none
real, parameter :: pi = 3.14159
www.yzyzfsxx.com/GNNMD1/
end module constants
module geometry
use constants
implicit none
contains
! 计算圆的面积
real function circle_area(radius)
real, intent(in) :: radius
circle_area = pi * radius**2
end function circle_area
end module geometry
module main_program
use geometry
implicit none
real :: r = 2.0
real :: area
! 使用几何模块中的子程序计算圆的面积
area = circle_area(r)
! 打印结果
print *, 'Radius = ', r
print *, 'Area = ', area
end module main_program
program use_modules
use main_program
implicit none
! 调用主程序模块中的程序
call main_program
end program use_modules
代码解释
多模块结构: 使用多个模块 constants、geometry 和 main_program 来组织程序,每个模块负责不同的功能。模块间的依赖: 使用 use 语句将一个模块引入到另一个模块中,以便共享数据和子程序。程序调用: 在 use_modules 主程序中调用 main_program 模块,间接调用了 geometry 模块中的子程序来计算圆的面积。打印结果: 使用 print 语句打印计算得到的圆的半径和面积。编译和运行
要编译并运行上述代码,可以使用如下命令:
bash
复制代码
gfortran constants.f90 geometry.f90 main_program.f90 use_modules.f90 -o use_modules
./use_modules
结论
通过上述示例,可以看到Fortran中利用模块化编程技术组织和管理程序结构的方法。模块化编程不仅有助于提高代码的可读性和可维护性,还能够促进代码重用和模块间的数据共享。在实际应