我有一个永不停止执行的fortran程序。
program russianmultiplication
implicit none
integer::x,y,ginx,giny,k=0
print*,'give a number'
read*,x
k=k+x
print*,'one more'
read*,y
if (y==1) then
print*,x
end if
do while(y/=1)
ginx=x*2
giny=y/2
if (mod(giny,2)/=0) then
k=k+ginx
end if
end do
print*,'result',k
end program
为什么这个程序永远不会结束?
答案 0 :(得分:1)
你永远不会在循环中更改y
,也没有exit
语句。因此,y
在输入时是1
,在这种情况下,循环的条件永远不会为真且永远不会执行,或者您永远不会离开循环,因为条件始终为真。
答案 1 :(得分:0)
这可能是原始程序Russian peasant multiplication的更清晰版本:
PROGRAM Russian_peasant_multiplication
IMPLICIT NONE
INTEGER :: total, x, x_save, y, y_save
total = 0!running total
PRINT *, "x ="
READ *, x
x_save = x
total = total + x
PRINT *, "y ="
READ *, y
y_save = y
PRINT *, y, x
!do while(y/=1)
modulo: DO
IF (y == 1) EXIT!replace DO WHILE for better control
!ginx=x*2
x = x * 2!okay to redefine since saved
!giny=y/2
y = y / 2!okay to redefine since saved
!if (mod(giny,2)/=0) then
IF (MOD(y, 2) /= 0) THEN!keep only odd numbers on the left
PRINT *, y, x
!k=k+ginx
total = total + x
END IF
END DO modulo
PRINT *, " "
PRINT *, x_save
PRINT *, "x"
PRINT *, y_save
PRINT *, "="
PRINT *, total
END PROGRAM Russian_peasant_multiplication
我添加了有用的评论,并指出逻辑存在缺陷的地方。希望这会有所帮助。