【发布时间】:2014-07-13 14:36:23
【问题描述】:
所以我正在尝试编写一个气泵程序。它的编译和工作,但我唯一的问题是当我打印出最终数量的加仑和费用时。当我按 q 然后进入退出循环并得到答案时,它会再增加一次。查看 displaycalc() 函数。
#include <iostream>
using namespace std;
class GasPump
{
private:
double gallons;
double charge;
double gasInTank ;
double costPerGallonReg;
double costPerGallonPlus;
double costPerGallonSup;
double costPerGallonChoice;
public:
void regularSetting();
void setPricePerGallon(double,double,double);
double getPricePerGallon();
void displayCalc();
};
//first function
void GasPump::regularSetting()
{
gallons = 0;
charge = 0;
gasInTank = 10.0;
cout<<"Price "<<charge<<endl;
cout<<"Gallons "<<gallons;
}
void GasPump::setPricePerGallon(double reg, double plus, double super)
{
cout<<"\n\nPlease choose type of gas you want to Purchase\n";
cout<<"\nRegular: "<<reg<<" Plus: "<<plus<<" Premium: "<<super;
//setting prices
costPerGallonReg = reg;
costPerGallonPlus = plus;
costPerGallonSup = super;
}
double GasPump::getPricePerGallon()
{
char choice;
cout <<"\nEnter r/R for Regular, p/P for Plus, or s/S for Super.\n";
cin >>choice;
if ((choice == 'R' || choice == 'r'))
{
return costPerGallonChoice = costPerGallonReg ;
}
else if ((choice == 'P'|| choice == 'p'))
{
return costPerGallonChoice = costPerGallonPlus ;
}
else if ((choice == 'S'|| choice == 's'))
{
return costPerGallonChoice = costPerGallonSup ;
}
else
{
cout<<"Invalid";
}
}
void GasPump::displayCalc()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
char choice;
system("cls");
cout<<"Press Enter to start filling and q to quit\n";
cout<<"Price "<<charge<<endl;
cout<<"Gallons "<<gallons<<endl;
while(gasInTank > 0)
{
choice = cin.get();
if((choice =='Q'||choice =='q'))
break;
system("cls");
cout<<"$"<<charge<<" ";
cout<<"Gallons "<<gallons<<endl;
charge += costPerGallonChoice * 0.1;
gallons += 0.1;
gasInTank -= 0.1;
}
cout<<"\nThank you for your purchase\n";
cout<<"Gallons: "<<gallons<<" $"<<charge;
}
int main()
{
//naming class
GasPump pump;
cout<<"Gas pump Program\n\n";
pump.regularSetting();
pump.setPricePerGallon(1.69,1.79,1.89);
pump.getPricePerGallon();
pump.displayCalc();
getchar();getchar();
return 0;
}
【问题讨论】: