我正在嘗試編寫一個程序,向用戶返回用於輸入用戶輸入的美元金額(美元)的最小金額美國硬幣。C似乎有效0.1比較被跳過
我的問題:當程序達到0.1時,程序不會減去一角錢,而是減去鎳和5便士。這隻發生在大於1.85的數字上。當小於1.85時,一角錢被成功扣除。
這裏是我的代碼:
while (Money >= 0.25){
Money = Money - 0.25;
Coins = Coins + 1;
printf ("Current money: %f \n", Money);
}
while (Money >= 0.1) {
Money = Money - 0.1;
Coins = Coins + 1;
printf ("Current money: %f \n", Money);
}
while (Money >= 0.05) {
Money = Money - 0.05;
Coins = Coins + 1;
printf ("Current money: %f \n", Money);
}
while (Money >= 0.01) {
Money = Money - 0.01;
Coins = Coins + 1;
printf ("Current money: %f \n", Money);
}
下面是當使用數字2.1我的輸出:
2.1
Current money: 1.850000
Current money: 1.600000
Current money: 1.350000
Current money: 1.100000
Current money: 0.850000
Current money: 0.600000
Current money: 0.350000
Current money: 0.100000
Current money: 0.050000
Current money: 0.040000
Current money: 0.030000
Current money: 0.020000
Current money: 0.010000
Used 13
而這個用數字1.85,當是我的輸出:
1.85
Current money: 1.600000
Current money: 1.350000
Current money: 1.100000
Current money: 0.850000
Current money: 0.600000
Current money: 0.350000
Current money: 0.100000
Current money: 0.000000
Used 8
這是爲什麼發生?爲什麼硬幣不能用於大於1.85的數字?
您應該閱讀 - http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html不應該使用浮點數進行貨幣計算,而應該使用固定點(並且一些可接受的四捨五入)。 – 2012-12-28 20:35:22
@VladLazarenko喜歡它。感謝您的鏈接。 –