Fortran 95 Do-While循环在错误情况下不会退出

时间:2011-02-28 00:24:10

标签: fortran while-loop exit do-while fortran95

这是我的代码:

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

第一个循环(> = 25)应该在余数变为22时退出,但它再次运行并产生负数。即使条件是假的,为什么不退出?我正在使用IDEone.com的Fortran“编译器”,它似乎与Fortran 95类似。

1 个答案:

答案 0 :(得分:4)

你的DO循环很好。您只需要在每个循环中从remainder中减去正确的面额。例如,将您的第二个DO循环更改为:

        do while (remainder >= 10)
                remainder = remainder - 10
                print*,remainder
                d = d + 1       
        end do

以类似的方式改变其余部分。