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

  • 本文关键字:模块 Fortran 程序 fortran
  • 更新时间 :
  • 英文 :


我建立了一个速度、距离和时间计算器。我想如果你能回到主菜单,在你最初的计算之后计算时间(作为一个例子),那将是很酷的。我如何通过使用模块来做到这一点?以下是我创建的模块:

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。虽然通常不建议在不同的例程中重用相同的变量,但这里这样做是为了说明如何"全局"。变量可以在模块级定义。

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

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

相关内容

  • 没有找到相关文章

最新更新