我不断收到类似以下的错误:
pitstop.cpp:36:23: error: indirection requires pointer operand
('double' invalid)
cost = UNLEADED * gallons;
^ ~~~~~~~
pitstop.cpp:40:14: error: expected expression
cost = SUPER * gallons; ^
#include <iostream>
#include <iomanip>
using namespace std;
#define UNLEADED 3.45;
#define SUPER {UNLEADED + 0.10};
#define PREMIUM {SUPER + 0.10};
/*
Author: Zach Stow
Date:
Homework
Objective:
*/
double cost, gallons;
string gasType, finish, stop;
int main()
{
for(;;)
{
cout <<"Hi, welcome to Pitstop.n";
cout <<"Enter the type of gas you need:";
cin >> gasType;
cout << endl;
cout <<"Enter the amount of gallons you need:";
cin >> gallons;
cout << endl;
if(gasType == "finish" || gasType == "stop")break;
else if(gasType == "UNLEADED")
{
cost = UNLEADED * gallons;
}
else if(gasType == "SUPER")
{
cost = SUPER * gallons;
}
else if(gasType == "PREMIUM")
{
cost = PREMIUM * gallons;
}
}
cout <<"You need to pay:$" << cost << endl;
return(0);
}
不是c++
专家,但我确信,要定义常量,只需要使用#define
指令,后跟符号和要分配给它的值(即使值本身是一个表达式,即使这样的表达式引用了另一个常量),大括号和尾部分号就太多了:
// [...]
#define UNLEADED 3.45
#define SUPER (UNLEADED + 0.10)
#define PREMIUM (SUPER + 0.10)
//[...]
它在第一次尝试时就进行了这样的更正。
错误的原因是#define指令末尾的分号。
您也使用了不正确类型的括号,请尝试以下操作:
#define UNLEADED 3.45
#define SUPER (UNLEADED + 0.10)
#define PREMIUM (SUPER + 0.10)
请注意,当您使用#define指令时,#define后面的任何内容都会被替换到代码中。在这种情况下,在预处理器运行后,您的代码看起来是这样的:
else if(gasType == "UNLEADED")
{
cost = UNLEADED 3.45; * gallons;
}
else if(gasType == "SUPER")
{
cost = {UNLEADED + 0.10}; * gallons;
}
else if(gasType == "PREMIUM")
{
cost = PREMIUM {SUPER + 0.10}; * gallons;
}
出现indirection requires pointer operand
错误的原因是编译器试图解释以下语句:
* gallons;
因为*
运算符只有一个参数,所以它被解释为指针解引用,幸运的是,gallons
变量不是指针类型。如果gallon被声明为指针类型,即double cost, *gallons;
,而cin
不在那里,那么代码会编译,但不会执行您期望的操作,可能会抛出segfault。
用#define定义的宏可能非常强大,也非常危险。在c++中通常有更好的方法来实现目标。在这种情况下,UNLEADED
、SUPER_UNLEADED
和PREMIUM
可以声明为const double
类型,即
const double unleaded = 3.45;
const double super = unleaded + 0.10;
const double premium = super + 0.10;