所以我差不多完成了我的程序,但我不断收到一分钱。例如,当我输入6.01美元作为物品成本和10.00美元作为投标金额时,我得到的结果为3.99美元,但面额为3美元钞票,3季度,2角钱和3便士(应该是4) 。我该如何解决这个问题?
static int assignment_change() {
//Variables
float cost_of_item, amount_tendered, total;
int change, pennies, nickels, dimes, quarters, dollar, five_dollars;
//Input
std::cout << "What was the cost of the item ($0.00 - $20.00)? $";
std::cin >> cost_of_item;
std::cout << "What was the amount tendered (Max $20.00)? $";
std::cin >> amount_tendered;
if (cost_of_item <= 20 && cost_of_item >= 0 && amount_tendered <= 20 && amount_tendered >= 0 && amount_tendered > cost_of_item)
{
//Formulas
total = amount_tendered - cost_of_item;
change = (int)total * 100;
five_dollars = change / 500;
change %= 500;
dollar = change / 100;
change %= 100;
quarters = change / 25;
change = change % 25;
dimes = change / 10;
change %= 10;
nickels = change / 5;
change %= 5;
pennies = change / 1;
change %= 1;
//Output
//-----------------------------------------------------------
if (five_dollars >= 1)
std::cout << five_dollars << " five dollar bills" << std::endl;
else if (five_dollars == 0)
std::cout << "";
//-----------------------------------------------------------
if (dollar > 1)
std::cout << dollar << " one dollars bills" << std::endl;
else if (dollar == 0)
std::cout << "";
else if (dollar == 1)
std::cout << dollar << " one dollar bill" << std::endl;
//-----------------------------------------------------------
if (quarters > 1)
std::cout << quarters << " quarters" << std::endl;
else if (quarters == 0)
std::cout << "";
else if (quarters == 1)
std::cout << quarters << " quarter" << std::endl;
//-----------------------------------------------------------
if (dimes > 1)
std::cout << dimes << " dimes" << std::endl;
else if (dimes == 0)
std::cout << "";
else if (dimes == 1)
std::cout << dimes << " dime" << std::endl;
//-----------------------------------------------------------
if (nickels > 1)
std::cout << nickels << " nickels" << std::endl;
else if (nickels == 0)
std::cout << "";
else if (nickels == 1)
std::cout << nickels << " nickel" << std::endl;
//-----------------------------------------------------------
if (pennies > 1)
std::cout << pennies << " pennies" << std::endl;
else if (pennies == 0)
std::cout << "";
else if (pennies == 1)
std::cout << pennies << " penny" << std::endl;
//-----------------------------------------------------------
//std::cout << fixed << setprecision(2) << "Change from $" << amount_tendered << " for a cost of $" << cost_of_item << " is" << std::endl;
std::cout << "Total is " << total << std::endl;
}
else
std::cout << "*****Your input for the cost of the item or the amount that was to be tendered was outside the designated range.*****" << std::endl;
return 0;
}
答案 0 :(得分:0)
正如另一条评论中所提到的,将总数改为int total = amount_tendered*100 - cost_of_item*100;
并从那里开始工作要简单得多。