我不断地收到类似于以下错误的错误:
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);
}发布于 2015-07-02 00:31:52
错误的原因是#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变量不是指针类型。如果加仑被声明为指针类型,即double cost, *gallons;,而cin不存在,那么代码将编译,但不会按您的预期执行,可能会抛出一个分段错误。
使用# defined定义的宏可能非常强大,而且非常危险。在c++中通常有更好的方法来实现目标。在这种情况下,UNLEADED、SUPER_UNLEADED和PREMIUM可以声明为const double类型。
const double unleaded = 3.45; const double super = unleaded + 0.10; const double premium = super + 0.10;
https://stackoverflow.com/questions/31174020
复制相似问题