大家好,我这里有一个不寻常的问题。我编写了一个货币兑换器类,它根据购买的总金额和购买的金额确定作为找零的纸币和硬币的数量。例如,如果您要以 12.04 美元的价格购买某样东西并给了一张 20 美元的钞票,您将收到 7.96 美元的零钱。
输出将是:
0 twenty dollar bill(s)
0 ten dollar bill(s)
1 5 dollar bill(s)
2 1 dollar bills(s)
3 quarter(s)
2 dime(s)
1 penny(s)
现在问题是我必须使用指针或引用返回每张钞票和硬币的数字。
我的程序有两个函数 GetBills,它使用指向整数的指针来返回更改所需的 20 美元、10 美元、5 美元和 1 美元钞票的数量。
另一个是 GetCoins,它再次使用指向整数的指针来返回更改所需的四分之一角钱、五分钱和便士的数量。
我的问题是这个。我的 GetBills 没有在指针中存储任何值,但我的 GetCoins 是。如果我输入 12.04 作为购买价格和 20.00 给定数量,我的输出是:
0 twenty dollar bill(s)
0 ten dollar bill(s)
0 5 dollar bill(s)
0 1 dollar bills(s)
3 quarter(s)
2 dime(s)
1 penny(s)
所以你可以看到一些硬币的价值很好但不是钞票。什么可能导致我的 GetBills 中的指针无法存储正确的值?
这是我的缩短代码:
MoneyChanger.h
class MoneyChanger
{
private:
double amountP, amountG, totalChange;
int twenty, ten, five, one, change;
int quarter, dime, nickel, penny;
public:
void GetBills(int *twenties, int *tens, int *fives, int *ones);
void GetCoins(int *quarters, int *dimes, int *nickels, int *pennies);
};
MoneyChanger.cpp
void MoneyChanger::setData(double pp, double given)
{
amountP = pp;
amountG = given;
CalcChange();
}
void MoneyChanger::CalcChange()
{
while(totalChange >= 20){totalChange = totalChange-20; twenty++;}
while(totalChange >= 10){totalChange = totalChange-10; ten++;}
while(totalChange >= 5){totalChange = totalChange-5; five++;}
while(totalChange >= 1){totalChange = totalChange-1; one++;}
while(totalChange >= .25){totalChange = totalChange-.25; quarter++;}
while(totalChange >= .10){totalChange = totalChange-.10; dime++;}
while(totalChange >= .05){totalChange = totalChange-.05; nickel++;}
while(totalChange >= .01){totalChange = totalChange-.01; penny++;}
}
double MoneyChanger::GetTotalChange()
{
totalChange = amountG - amountP;
return totalChange;
}
void MoneyChanger::GetBills(int *twenties, int *tens, int *fives, int *ones)
{
*twenties = twenty;
*tens = ten;
*fives = five;
*ones = one;
CalcChange();
}
void MoneyChanger::GetCoins(int *quarters, int *dimes, int *nickels, int *pennies)
{
*quarters = quarter;
*dimes = dime;
*nickels = nickel;
*pennies = penny;
CalcChange();
}
主文件
int main()
{
MoneyChanger mc;
int twenties, tens, fives, ones, quarter, dimes, nickels, pennies;
double purchase, given;
cout<<"please enter total cost of purchase: ";
cin>>purchase;
cin.ignore();
cout<<"\nplease enter amount given: ";
cin>>given;
mc.setData(purchase, given);
cin.ignore();
cout<<"Your change is: "<<mc.GetTotalChange()<<"\n\n";
mc.GetBills(&twenties, &tens, &fives, &ones);
mc.GetCoins(&quarter, &dimes, &nickels, &pennies);
cout<<twenties<<" twenty dollar bill(s)"<<endl;
cout<<tens<<" ten dollar bill(s)"<<endl;
cout<<fives<<" five dollar bill(s)"<<endl;
cout<<ones<<" one dollar bill(s)"<<endl;
cout<<quarter<<" quarter(s)"<<endl;
cout<<dimes<<" dime(s)"<<endl;
cout<<nickels<<" nickel(s)"<<endl;
cout<<pennies<<" penny(s)"<<endl;
return 0;
}