Fortran 95 Do-While 循环在错误条件下不退出
这是我的代码:
program change
integer:: amount, remainder, q, d, n, p
amount = 47
remainder = amount
print*,remainder
q = 0
d = 0
n = 0
p = 0
do while (remainder >= 25)
remainder = remainder - 25
print*,remainder
q = q + 1
end do
do while (remainder >= 10)
remainder = remainder - 25
print*,remainder
d = d + 1
end do
do while (remainder >= 5)
remainder = remainder - 25
print*,remainder
n = n + 1
end do
do while (remainder >= 1)
remainder = remainder - 25
print*,remainder
p = p + 1
end do
print*, "# Quarters:", q
print*, "# Dimes:", d
print*, "# Nickels:", n
print*, "# Pennies:", p
end program change
输出:
47
22
-3
# Quarters: 1
# Dimes: 1
# Nickels: 0
# Pennies: 0
一旦余数变为 22,第一个循环 (>=25) 应该退出,但它会再次运行并产生负数。即使条件为假,为什么它不退出?我正在使用 IDEone.com 的 Fortran“编译器”,它看起来与 Fortran 95 类似。
Here is my code:
program change
integer:: amount, remainder, q, d, n, p
amount = 47
remainder = amount
print*,remainder
q = 0
d = 0
n = 0
p = 0
do while (remainder >= 25)
remainder = remainder - 25
print*,remainder
q = q + 1
end do
do while (remainder >= 10)
remainder = remainder - 25
print*,remainder
d = d + 1
end do
do while (remainder >= 5)
remainder = remainder - 25
print*,remainder
n = n + 1
end do
do while (remainder >= 1)
remainder = remainder - 25
print*,remainder
p = p + 1
end do
print*, "# Quarters:", q
print*, "# Dimes:", d
print*, "# Nickels:", n
print*, "# Pennies:", p
end program change
Output:
47
22
-3
# Quarters: 1
# Dimes: 1
# Nickels: 0
# Pennies: 0
The first loop (>=25) should exit once the remainder becomes 22, but it runs through once more and yields a negative number. Why is this not exiting even though the condition is false? I'm using IDEone.com's Fortran "compiler" which appears to be Fortran 95-like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的 DO 循环没问题。您只需在每个循环中从余数中减去正确的面额即可。例如,将第二个 DO 循环更改为:
并以类似的方式更改其余部分。
Your DO loops are fine. You simply need to subtract the correct denomination from
remainder
in each loop. For instance change your second DO loop to:and change the rest in a similar manner.