我試圖製作一個程序,需要輸入金額並將它們分成多少個硬幣纔會相等。到目前爲止,我寫的大部分時間都給了我合適的金額,但有時候它會是一分錢,我不知道爲什麼。試圖製作一個程序,將金額分爲硬幣
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
如果你看看[這裏](https://ideone.com/OHhyCJ),你會發現它實際上是1.99 ... 62,因爲浮點算法不準確。當您轉換爲整數時,小數位將被完全截斷。 – Li357