我正在尝试为票据转换器编写代码,其中插入的金额将转换回用户的硬币。问题是当我输入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);
}
答案 0 :(得分:1)
您的代码中基本上有两个错误:
int
或甚至unsigned int
。为简单起见,数量本身可以作为浮点数读入,但也应该将整数转换为整数,以避免舍入错误。else if
链,它只会考虑一种类型的硬币。先处理所有类型的硬币,高等面额,然后减少仍需处理的金额。请注意,使用10c作为最小硬币,您可能无法对所有金额进行全面更改。这是没有外部循环且没有奇怪的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;
}
答案 1 :(得分:0)
要强制amount
具有整数值,您应该在除法后对值进行舍入:
if(amount>=50)
{
remainder=round(amount/50);
sum50c=remainder;
}