找出谐波串联求和大于整数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
答案 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