这是提示我还没有得到所有这些但是:
实施一个名为GasPump的类,用于在加油站对泵进行建模。 GasPump对象应该能够执行以下任务: - 显示分配的气体量 - 显示分配的气体总量 - 设定每加仑汽油的成本 - 显示每加仑汽油的成本 - 在每次新使用之前重置分配的气体量和充电量 - 跟踪分配的气体量和总电量
在实施GasPump等级时,您应该假设气泵已经分配 每秒.10加仑的汽油。在main()中编写一个提示用户的测试程序 输入每加仑汽油的成本和他们想要抽出汽油的秒数。 然后,显示泵送的加仑气体的数量,每加仑气体的成本,和 天然气的总成本。
我在计算支付金额时遇到问题,并且一直遇到逻辑错误。由于这个代码代表它会编译,但它会为计算收费金额提供垃圾。
#include <iostream>
#include <iomanip>
using namespace std;
class GasPump{
public:
void setCostPerGallon(double cpg){
costPerGallon = cpg;
}
double getCostPerGallon(){
return costPerGallon;
}
void setAmountDispensed(int seconds){
const double dispense = 0.10;
sec = seconds;
amountDispensed = dispense * sec;
}
int getAmountDispensed(){
return amountDispensed;
}
//here is the function I am having problems with, at least I think.
void setAmountCharged(double costPerGallon, double amountDispensed){
amountCharged = costPerGallon * amountDispensed;
}
double getAmountCharged(){
return amountCharged;
}
private:
double costPerGallon;
int sec;
double amountCharged, amountDispensed;
};
int main() {
double cpg = 0.0;
int seconds = 0;
GasPump pump;
cout << "Enter the cost per gallon of gas:";
cin >> cpg;
while(cpg <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> cpg;
}
pump.setCostPerGallon(cpg);
cout << "Enter the amount of seconds you want to pump gas for:";
cin >> seconds;
while(seconds <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> seconds;
}
pump.setAmountDispensed(seconds);
cout << "The gas pump dispensed " << pump.getAmountDispensed() << " gallons of gas." << endl
<< "At $" << pump.getCostPerGallon() << " per gallon, your total is $"
<< fixed << setprecision(2) << pump.getAmountCharged() << "." << endl;
return 0;
答案 0 :(得分:0)
您永远不会调用pump.setAmountCharged(...)
,因此成员变量amountCharged
是编译器在您实例化pump
时通常将其初始化的任何内容(通常为0);
要解决此问题,请先删除成员变量amountCharged
,然后在调用getAmountCharged
时计算金额,或在调用setAmountCharged
之前适当调用getAmountCharged
这是第一个解决方案:
class GasPump {
...
double getAmountCharged() {
return costPerGallon * amountDispensed;
}
...
};