一元'*'的无效类型参数(有双)

问题描述 投票:0回答:3

刚开始学习c ++有这个错误:

C:\Users\KC\Documents\Math.cpp|9|error: invalid type argument of unary '*' (have 'double')|

这是代码:

#include <iostream>
#include <cmath>
#define M_PI
using namespace std;

int main()
{
   double area, radius = 1.5;
      area = M_PI * radius * radius;
   cout << area << "\n";
}

谁能向我解释我做错了什么。谢谢

c++
3个回答
3
投票
#define M_PI

应该

#define M_PI 3.14159

(或者你想给pi的任何价值)。

您将M_PI定义为无,这意味着此代码

  area = M_PI * radius * radius;

成为这个代码

  area = * radius * radius;

并且你的编译器抱怨意外的*


2
投票

我建议使用:

#define _USE_MATH_DEFINES
#include <cmath>

并删除此行:

#define M_PI

更多信息在这个答案:M_PI works with math.h but not with cmath in Visual Studio


1
投票

您使用预处理器指令#define M_PIM_PI定义为空字符串。因此,在将空内容替换为M_PI后,表达式

area = M_PI * radius * radius

成为

area = * radius * radius

并且第一个星号成为一元运算符,整个表达式被解释为

area = (* radius) * radius

这个一元星号不能合理地使用double参数,因此是错误信息。

© www.soinside.com 2019 - 2024. All rights reserved.