c++在类中传递变量并获得逻辑错误
C++ passing variables in classes and getting logical errors
这是提示符我还没有全部讲到
实现一个名为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;
}
...
};
相关文章:
- 提升错误:变量"TimeSpec RQTP"具有初始值设定项,但类型不完整
- C++ SPDLOG 编译错误:变量或字段"set_error_handler"声明为无效
- 错误 - 变量类型 "X" 是一个抽象类 - c++
- 带有 std::map 的模板函数给出错误:变量或字段声明为 void
- C 错误变量大小对象可能不会初始化
- 我收到错误"变量类型不完整"无效,我找不到问题所在
- C++以友元身份重载 ostream 运算符会导致错误:变量在此上下文中是私有的
- 错误:变量未在此范围内声明
- 错误:变量未在此范围 C++ 中声明
- 无法访问获取错误变量
- C++错误"变量或字段声明为无效"
- 错误:变量需要堆栈帧
- VS2010 中 C++ lambda 表达式的奇怪错误(变量 y1 )
- 我不断收到错误"变量'b'未初始化正在使用,我不确定如何解决它
- 如何更正运行时错误变量周围的堆栈已损坏
- 错误变量受保护
- 线程池的 lambda 函数内的编译器错误变量"未捕获"
- 接收错误变量的类型不完整"void"
- 运行时错误-变量arr_processes周围的堆栈已损坏
- 错误:变量未在此范围内声明