2011-02-28 74 views
2

這裏是我的代碼: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 

第一個循環(> = 25)應該退出,一旦餘數22 ,但它會再次運行併產生一個負數。即使條件不成立,爲什麼這不會退出?我正在使用IDEone.com的Fortran「編譯器」,它看起來像Fortran 95一樣。

回答

4

你的DO循環很好。您只需在每個循環中從remainder中減去正確的面額。例如,將您的第二個DO循環更改爲:

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

並以類似方式更改其餘部分。

+0

哇!我完全錯過了我複製粘貼一切的事實!謝謝。 – jmdefran 2011-02-28 06:33:21