如何在 Fortran 90 中打印进度条?

问题描述 投票:0回答:1

我是 Fortran 新手。我正在尝试在 Fortran 90 中编写一个子例程,在循环内调用时打印进度条。尽管我的进度条代码作为独立程序运行良好,但当我将其移动到子例程时它停止工作。它不是打印单个进度条,而是打印 n 个进度条副本。我正在使用 gfortran 编译器。

我正在尝试使用此进度条来跟踪循环中正在完成的计算的进度。

我只是不明白为什么在循环内有

write
语句的原始程序可以完美地工作,但是当我删除循环并将代码移至子例程时,它停止工作。

输出是这样的:

 progress:  99.9 %[||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||] 

 progress:  99.9 %[||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||] 

我的子程序代码如下

subroutine print_progress_bar(progress) 
implicit none
    real, intent(in) :: progress
    integer :: i
    integer :: PBWIDTH = 60
    character(len=60) :: PBSTR = "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
    character(len=60) :: CTPBSTR
    integer :: val
    integer :: lpad
    integer :: rpad
    
    write(*, *)
    write(*, '(a17)', advance='no') ' Progress : 00.0%'
    
    ! Test the progress bar by incrementing progress
      
    val = int(progress * 100)
    lpad = int(progress * (PBWIDTH + 1))
    rpad = PBWIDTH - lpad
    CTPBSTR = PBSTR(1:lpad)
    CTPBSTR(lpad + 1: PBWIDTH) = ' '
    
    
    write(*,'(a, a, f5.1, a2, a1, a1)', advance="no") & 
          char(13), ' progress: ', progress*100, '%'
    write(*, "(A)", advance="no") "["
    write(*, "(A)", advance="no")  CTPBSTR
    write(*, "(A)", advance="no") "]"
    write(*, *) ""
    
    flush(6)

end subroutine print_progress_bar

我从 do 循环中调用它,如下所示

progress = 0.00

do i = 1, atomCount 

    call print_progress_bar(progress)

    progress = i / real(atomCount - 1)
    
end do

我原来的代码如下:

program test_progress_bar 
  implicit none

    real :: progress
    integer :: i
    integer :: PBWIDTH = 60
    character(len=60) :: PBSTR = "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
    character(len=60) :: CTPBSTR
    integer :: val
    integer :: lpad
    integer :: rpad
    
    progress = 0.01
  
    write(*, *)
    write(*, '(a17)', advance='no') ' Progress : 00.0%'

    ! Test the progress bar by incrementing progress
    do i = 1, 100 
      
      val = int(progress * 100)
      lpad = int(progress * (PBWIDTH + 1))
      rpad = PBWIDTH - lpad
      CTPBSTR = PBSTR(1:lpad)
      CTPBSTR(lpad + 1: PBWIDTH) = ' '
      
      
      write(*,'(a, a, f5.1, a2, a1, a1)', advance="no") &
            char(13), ' progress: ', progress*100, '%'
      write(*, "(A)", advance="no") "["
      write(*, "(A)", advance="no")  CTPBSTR
      write(*, "(A)", advance="no") "]"

      progress = progress + 0.01


      call sleep(1)
    end do
    
    write(*, *) ""

end program test_progress_bar

谢谢

fortran progress-bar fortran90
1个回答
0
投票

为了防止它对某人有帮助,我设法通过执行以下操作解决了该问题:

首先我删除了临时变量

progress
,然后删除了对
print_progress_bar
子例程的调用,然后再次添加它,如下:

    do i = 1, atomCount 

        call print_progress_bar(real(i)/real(atomCount))

    end do

我完全不知道为什么这可以解决问题,但它确实解决了。

© www.soinside.com 2019 - 2024. All rights reserved.