C++ 在 类 中传递变量并出现逻辑错误

C++ passing variables in classes and getting logical errors

这里是我还没有完全理解的提示:

实现一个名为 GasPump 的 class,它将用于模拟加油站的泵。 GasPump 对象应该能够执行以下任务: - 显示分配的气体量 - 显示分配的气体量的总计费用 - 设置每加仑汽油的成本 - 显示每加仑汽油的成本 - 在每次新使用前重置分配的气体量和充电量 - 跟踪分配的气体量和总电量

实施 GasPump class 时,您应该假定气泵分配 .10 加仑气体每秒。在 main() 中编写一个测试程序,提示用户 输入每加仑汽油的成本以及他们想要抽气的秒数。 然后,显示泵送的汽油加仑数、每加仑汽油的成本,以及 gas 的总成本。

我在计算支付金额时遇到问题,并且不断出现逻辑错误。就此代码而言,它可以编译,但它会为计算收取的金额提供垃圾。

#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;

您永远不会调用 pump.setAmountCharged(...),因此成员变量 amountCharged 是编译器在您实例化 pump(通常为 0)时决定将其初始化的值;

要解决这个问题,要么删除成员变量 amountCharged 并在调用 getAmountCharged 时计算金额,或者在调用 [=15] 之前适当地调用 setAmountCharged =].

这是第一个解决方案:

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