如何在 Fortran 程序中正确使用模块?

How do I use modules correctly in a Fortran program?

我构建了一个速度、距离和时间计算器。我认为如果您可以在原始计算后返回主菜单并计算时间(作为示例),那会很酷。我将如何通过使用模块来做到这一点?以下是我创建的模块:

module menu
  real :: s ! speed
  real :: d ! distance
  real :: t ! time
  real :: gg ! this is how I am going to switch between distance, time, and speed

  print *, 'Press 1 for speed, 2 for distance, and 3 for time'
  read*, gg
end menu

module speed
  print *, 'Input distance in metres'
  read *, d 
  print *, 'Input time in seconds'
  read *, t 
  s = d / t
  print *, 'Speed is ', s
end speed

module stay or leave
  print *, 'Press 4 to go back to menu, or press 5 to exit the console'
  read *, gg
end stay or leave

module distance
  print *, 'Input speed in metres per second'
  read *, s
  print *, 'Input time in seconds'
  read *, t 
  d = s * t
  print*, 'Distance is ', d
end distance

module time
  print *, 'Input distance in metres'
  read *, d
  print *, 'Input speed in metres per second'
  read *, s 
  t = d / s
  print*, 'Time is ', s 
end time

您正在使用 module 作为子程序。模块是相关子程序、用户类型和其他相关数据的集合。在这个例子中不需要使用模块(至少不是上面显示的方式)。

但是如果您不得不使用模块,我在下面提供了一个示例。模块定义包含以下子例程

  • time_from_distance_and_speed()
  • distance_from_speed_and_time()
  • speed_from_time_and_distance()

和计算中使用的三个常用变量t, d, s。虽然通常不建议 re-using 在不同的例程中使用相同的变量,但这里这样做是为了说明目的,以说明如何在模块级别定义“全局”变量。

模块

这里的模块包含变量定义,这些变量定义对于它包含的过程是通用的。它还定义了三个计算过程。

module kinematics
implicit none
real :: t, d, s

contains

subroutine time_from_distance_and_speed()
print *, 'Input distance in metres'
read *, d
print *, 'Input speed in metres per second'
read *, s 
t = d / s
print*, 'Time is ', s 
end subroutine

subroutine distance_from_speed_and_time()
print *, 'Input speed in metres per second'
read *, s
print *, 'Input time in seconds'
read *, t 
d = s * t
print*, 'Distance is ', d
end subroutine

subroutine speed_from_time_and_distance()
print *, 'Input distance in metres'
read *, d 
print *, 'Input time in seconds'
read *, t 
s = d / t
print *, 'Speed is ', s
end subroutine

end module

计划

这里主程序使用上面定义的模块并根据用户输入调用适当的方法。

program bike
use kinematics
integer :: gg
do while(.true.)
    print *, 'Press 1 for speed, 2 for distance, and 3 for time'
    read*, gg
    if(gg == 1) then
        call speed_from_time_and_distance
    else if(gg == 2) then
        call distance_from_speed_and_time
    else if(gg == 3) then
        call time_from_distance_and_speed
    end if
    print *, 'Press 5 to exit the console, anything else will repeat'
    read *, gg    
    if(gg== 5) then
        exit
    end if
end do

end program