2016-10-08 22 views
0

我試圖製作一個程序,需要輸入金額並將它們分成多少個硬幣纔會相等。到目前爲止,我寫的大部分時間都給了我合適的金額,但有時候它會是一分錢,我不知道爲什麼。試圖製作一個程序,將金額分爲硬幣

public static void main(String[] args) { 
    double amount; 
    System.out.println("This program will display the number of " 
      + "quarters, dimes, nickels and pennies based on the " 
      + "amount you enter below."); 
    System.out.println(); 
    System.out.print("Please enter an amount: "); 
    Scanner scan = new Scanner(System.in); 
    amount = scan.nextDouble(); 

    double quarter = amount/0.25; 
    amount = amount % 0.25; 
    double dime = amount/0.10; 
    amount = amount % 0.10; 
    double nickel = amount/0.05; 
    amount = amount % 0.05; 
    double penny = amount/0.01; 


    System.out.println("Quarters: " + (int)quarter); 
    System.out.println("Dimes " + (int)dime); 
    System.out.println("Nickels " + (int)nickel); 
    System.out.println("Pennies " + (int)penny); 

當我輸入2.47,我得到:

Please enter an amount: 2.47 
Quarters: 9 
Dimes: 2 
Nickels: 0 
Pennies: 2 

但是,當我輸入1.47,我得到:

Please enter an amount: 1.47 

Quarters: 5 
Dimes: 2 
Nickels: 0 
Pennies: 1 
+0

如果你看看[這裏](https://ideone.com/OHhyCJ),你會發現它實際上是1.99 ... 62,因爲浮點算法不準確。當您轉換爲整數時,小數位將被完全截斷。 – Li357

回答

0

有關問題的最可能的原因是浮點運算受四捨五入錯誤影響。在某個點上,其中一箇中間浮點結果不完全準確,並且當您使用強制轉換將double轉換爲int時,錯誤是放大

對於爲什麼這樣的事情發生在一個完整的解釋,閱讀答案Is floating point math broken?

解決方案,您應該這樣使用int(或long)類型來表示美分的整數重新編碼。

開始與此:

long amount = (long) (100 * scan.nextDouble()); 

,然後相應地重新編碼的方法的其餘部分。

+0

如果它是現有問題的重複,請將CV作爲此類:)。必要時評論其他細節。 – Li357