[英]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.