2015-09-27 67 views
-1

这是我没有得到所有的它尚未虽然提示:C++传递类变量和获取逻辑错误

实现一个类名为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

精心制作的关于你的_logic errors_请。请发布[MCVE]。 –

+0

很抱歉忘记发布输出,如下所示: 输入每加仑气体的成本:4.25 输入您希望泵送气体的秒数:342 气体泵分配了34加仑的气体。 每加仑4.25美元,你的总价是-0.00美元。 – oversizedsamuri

+0

“保持逻辑错误”不是有效的问题描述。 –

回答

0

你永远不会调用pump.setAmountCharged(...),所以成员变量amountCharged无论是编译器决定将其初始化,当你实例化pump(通常为0);

为了解决这个问题,无论是摆脱成员变量amountCharged和用于当getAmountCharged被称为量做计算,或适当调用getAmountCharged之前调用setAmountCharged

这里的第一个解决方案:

class GasPump { 
    ... 
    double getAmountCharged() { 
     return costPerGallon * amountDispensed; 
    } 
    ... 
}; 
+0

我摆脱了'amountCharged',并使用您发布的解决方案,但我仍然得到相同的错误。 – oversizedsamuri

+0

意思是在原始代码中使用'amountDispensed'而不是'sec'。这是一个完整的解决方案[示例](http://coliru.stacked-crooked.com/a/7de06135596c5c01)。 – huu