我正在尝试为钞票兑换器编写代码,其中插入的金额将被转换回用户的硬币。问题是当我输入 111.111 时,我的 50c 中总是有小数,例如 222.222。我的 20c 和 10c 未使用..请帮忙
#include <stdio.h>
int main()
{
double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0;
double amount;
do
{
printf("Please enter an amount(dollars):");
scanf("%lf", &amount);
amount=amount*100;
if(amount<0){
printf("Invalid Input\n");
printf("Re-enter your amount:");
scanf("%lf", &amount);
}
if(amount>=50){
remainder=amount/50;
sum50c=remainder;
}else
if(remainder!=0){
remainder2=remainder/20;
sum20c=remainder2;
}else
if(remainder2!=0){
remainder3=remainder3/10;
sum10c=remainder3;
}
if(sum50c>200||sum20c>200||sum10c>200){
end++;
}else{
end=0;
}
}
while(end<=0);
printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c);
}
最佳答案
您的代码中基本上有两个错误:
- 此处不要对 float 进行运算。硬币的数量将是一个离散数字,应表示为
int
甚至可能是unsigned int
。为了简单起见,金额本身可以作为 float 读取,但也应该将其转换为整数形式的美分,以避免舍入错误。 - 你必须找到硬币的组合:30c 是 1% 倍;20c + 1×10c。这意味着您不能使用
else if
链,它只会考虑一种类型的硬币。处理所有类型的硬币,先提高面额,然后减少仍要处理的数量。请注意,由于 10 美分是最小的硬币,您可能无法全额找零。
这是没有外循环且没有奇怪的 end
业务的示例:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int num50c = 0,
num20c = 0,
num10c = 0;
int amount; // amount in cents
double iamount; // input amount in dollars
printf("Please enter an amount: ");
scanf("%lf", &iamount);
amount = iamount * 100 + 0.5;
if (amount < 0) {
printf("Invalid Input\n");
exit(1);
}
num50c = amount / 50;
amount %= 50;
num20c = amount / 20;
amount %= 20;
num10c = amount / 10;
amount %= 10;
printf("%d x 50c = %d\n", num50c, num50c * 50);
printf("%d x 20c = %d\n", num20c, num20c * 20);
printf("%d x 10c = %d\n", num10c, num10c * 10);
printf("Remainder: %dc\n", amount);
return 0;
}
关于c - 尝试为钞票兑换机/硬币自动售货亭编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496560/