c++在类中传递变量并获得逻辑错误

C++ passing variables in classes and getting logical errors

本文关键字:错误 变量 c++      更新时间:2023-10-16

这是提示符我还没有全部讲到

实现一个名为GasPump的类,该类将用于为加油站的泵建模。一个GasPump对象应该能够执行以下任务:-显示气体分配量-显示总金额收取的气体分配量-设定每加仑汽油的成本-显示每加仑汽油的成本-重置每次使用前分配的汽油量和收费金额-跟踪分配的气体量和总费用

在实现GasPump类时,应该假设气泵分配每秒0.1加仑的气体。在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;

您从未调用过pump.setAmountCharged(...),因此成员变量amountCharged是在您实例化pump时编译器决定初始化它的值(通常为0);

要解决这个问题,要么去掉成员变量amountCharged,并在调用getAmountCharged时计算数量,要么在调用getAmountCharged之前适当地调用setAmountCharged

这是第一个解决方案:

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