我刚完成我的更改计算器(根据购买成本和给定的现金计算更改)。我正在测试它,看看它是否有效,并发现一个错误。只要给出的便士数量恰好为1,就表示它为0.我浏览了代码,并手动完成了我写的代码(不运行它)的代码,它看起来应该可以工作。如果你想自己测试这个,只需将0作为购买成本,36.91作为现金。 (这意味着变化是36.91,它应该是1个20,1,1,10,1半美元,1个季度,1个硬币,1个镍和1个便士[但它表示0个便士]。 :我很新的C++和了解很少更改计算器不计算便士
这里是代码:
/*This program simulates a situation at the register where someone pays with cash
and the cashier needs to know how much change and of which coins he or she needs to give.
Written by Jay Schauer
*/
//Data Declarations
#include <iostream>
#include <cstdint>
int main()
{
using namespace std;
double cost; //Stores cost of purchase
cout << "Input cost of purchase (in USD)" << endl;
cin >> cost;
double cash; //Stores cash that pays for purchase
cout << "Input cash given (in USD)" << endl;
cin >> cash;
double changet = cash - cost; //Stores the change,
the t is for temporaary because I use a different change variable later
cout << "Change to be given is " << changet << " in..." << endl;
//Also, I thought this was pretty clever since doubles apparantly can't be used
//with modulus (it gave me an error),
//so I figured I just multiply it by 100 and multiply all the divisions by 100 also
changet *= 100;
int change = changet; //Converts changet to an integer to be used with the modulus
int coins; //Stores the amount of "coins" to be given as change
coins = change/2000;
cout << coins << " twenty dollar bills" << endl;
change = change % 2000;
coins = change/1000;
cout << coins << " ten dollar bills" << endl;
change = change % 1000;
coins = change/500;
cout << coins << " five dollar bills" << endl;
change = change % 500;
coins = change/100;
cout << coins << " one dollar bills" << endl;
change = change % 100;
coins = change/50;
cout << coins << " half dollars" << endl;
change = change % 50;
coins = change/25;
cout << coins << " quarters" << endl;
change = change % 25;
coins = change/10;
cout << coins << " dimes" << endl;
change = change % 10;
coins = change/5;
cout << coins << " nickels" << endl;
change = change % 5;
//There is one problem that I can't figure out
//If the number of pennies to be given for change is exactly 1,
//it says 0 for the number of pennies to be given as change
coins = change/1;
cout << coins << " pennies" << endl;
system("pause");
return 0;
}
您是否尝试过在开始时打印出“change”,看看它的价值是什么? – Barmar
顺便说一句,除1之外没有任何意义,根据定义,它什么也不做。 –
是的,在将其更改为整数之前将其打印出来。 –