[英]Counting the least amount of change to give your client
我試圖計算剩余的硬幣數量,以便為客戶提供最少的硬幣數量。
但是最后一個硬幣為0.01
總是會誤算它。
我總是得到硬幣數量-1
。
get_float()
是一個接受浮點輸入的特殊函數。
#include <stdio.h>
#include <cs50.h>
int main(void) {
float coin;
int count;
do {
coin = get_float("enter the owed change?");
//printf("your cash %f", coin);
printf("\n");
} while (coin <= 0.00 || coin > 1.00);
//if (coin > 0.000000 && coin < 1.000000) {
count = 0;
while ((coin - 0.25) > 0) {
coin -= 0.25;
count++;
}
while ((coin - 0.10) > 0) {
coin -= 0.10;
count++;
}
while ((coin - 0.05) > 0) {
coin -= 0.05;
count++;
}
while ((coin - 0.01) > 0) {
coin -= 0.01;
count++;
}
if (coin == 0.01) {
count++;
}
//if (coin == 0.00) {
printf("%d", count);
//}
//}
}
典型的float
可以精確編碼大約2 32個不同的值。
0.10,0.05,0.01 都不是。
而是使用附近的值。
正是這種近似導致了問題。
相反,請使用0.01
(分)的整數@Kamil Cuk :
// prototype for `round()`
#include <math.h>
do {
// coin = get_float("enter the owed change?");
coins = round(100.0 * get_float("enter the owed change?");
printf("\n");
// } while(coin<=0.00 || coin>1.00);
} while(coin <= 0 || coin > 100);
...
// while((coin-0.10)>0)
while((coin - 10) > 0)
浮點數不能代表一些餾分如0.1
, 0.05
和0.01
完全相同。 即使在總和coins
是不完全表示,除非它是0.75
, 0.5
或0.25
。 當您減去這些值時,會累積非常小的誤差,並導致比較產生意外的結果。
您應該小心地將總和轉換為美分的整數或在測試中考慮到不精確性。
此外,您的測試不正確:例如while ((coin - 0.25) > 0)
應該是while ((coin - 0.25) >= 0)
這是第一種方法的修改版本:
#include <math.h>
#include <stdio.h>
#include <cs50.h>
int main(void) {
float coin;
int cents;
int count;
do {
coin = get_float("enter the owed change?");
printf("\n");
} while (coin <= 0.00 || coin > 1.00);
cents = roundf(coin * 100);
count = 0;
while (cents >= 25) {
counts -= 25;
count++;
}
while (cents >= 10) {
cents -= 10;
count++;
}
while (cents >= 5) {
cents -= 5;
count++;
}
while (cents >= 1) {
cents -= 1;
count++;
}
printf("%d coins\n", count);
return 0;
}
可以簡化為:
#include <stdio.h>
#include <cs50.h>
int main(void) {
float coin;
int cents;
int count;
do {
coin = get_float("enter the owed change?");
printf("\n");
} while (coin <= 0.00 || coin > 1.00);
cents = round(coin * 100);
count = cents / 25;
cents %= 25;
count += cents / 10;
cents %= 10;
count += cents / 5;
cents %= 5;
count += cents;
printf("%d coins\n", count);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.