所以我试图写一个气泵程序。它正在编译和工作,但我唯一的问题是当我打印出最终的加仑量并充电时。当我按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<<"nnPlease choose type of gas you want to Purchasen";
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 quitn";
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 purchasen";
cout<<"Gallons: "<<gallons<<" $"<<charge;
}
int main()
{
//naming class
GasPump pump;
cout<<"Gas pump Programnn";
pump.regularSetting();
pump.setPricePerGallon(1.69,1.79,1.89);
pump.getPricePerGallon();
pump.displayCalc();
getchar();getchar();
return 0;
}
你的代码几乎是正确的,有2个问题:刷新cin
流并在while循环中移动cout
,代码如下:
cout<<"$"<<charge<<" ";
cout<<"Gallons "<<gallons<<endl;
放在while循环的末尾,比如
cin.ignore(1000, 'n');
cin.get();
cout<<"$"<<charge<<" ";
cout<<"Gallons "<<gallons<<endl; // if you really want to display the 0
while(gasInTank > 0)
{
choice = cin.get();
if((choice =='Q'||choice =='q'))
break;
system("cls");
// Move these 2 lines at the end
// cout<<"$"<<charge<<" ";
// cout<<"Gallons "<<gallons<<endl;
charge += costPerGallonChoice * 0.1;
gallons += 0.1;
gasInTank -= 0.1;
// moved here, now it's ok
cout<<"$"<<charge<<" ";
cout<<"Gallons "<<gallons<<endl;
}
否则在递增之前显示。基本上,当你按下第一个ENTER键时,你已经把汽油放进了油箱,变量增加了,但在你的原始代码中,你是在增加之前显示数量的。