在fortran行为中的do-if循环在截断谐波系列中行为不端

时间:2018-02-01 20:47:37

标签: fortran gfortran

找出谐波串联求和大于整数m所需的最小元素数。

我尝试了这段代码,但它总是给i = 1,我该怎么解决这个问题,如果这个程序完全错误,那么什么程序会给我系列所需的术语数量。我在最后添加了输出。请帮助。

program Harmonic
implicit none
integer :: i,m
double precision :: sum
sum=0.0

Print *, "What is the series limit M??"
Read (*,*) m


  do  i=1,i  

     sum= sum+1.0/i 
     print *, sum

     if ( sum>m ) exit             
  end do

 print *, "The harmonic series with", i,"elements is greater than", m


end program Harmonic

输出:

What is the series limit M??
10

The harmonic series with  1 elements is greater than 10

1 个答案:

答案 0 :(得分:2)

问题是变量i尚未初始化。循环“do i = 1,1”也会给你带来麻烦。使用“do while”应该更清楚。

program Harmonic
  implicit none
  double precision :: i,m,sum

  i = 0.
  sum = 0.

  print *, "What is the series limit M??"
  read (*,*) m

  do while ( sum < m )
     i = i + 1
     sum = sum + 1./i 
     ! print *, sum
  end do

  print *, "The harmonic series with", i,"elements is greater than", m

end program Harmonic