刚开始学习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";
}
谁能向我解释我做错了什么。谢谢
#define M_PI
应该
#define M_PI 3.14159
(或者你想给pi的任何价值)。
您将M_PI
定义为无,这意味着此代码
area = M_PI * radius * radius;
成为这个代码
area = * radius * radius;
并且你的编译器抱怨意外的*
。
我建议使用:
#define _USE_MATH_DEFINES
#include <cmath>
并删除此行:
#define M_PI
更多信息在这个答案:M_PI works with math.h but not with cmath in Visual Studio
您使用预处理器指令#define M_PI
将M_PI
定义为空字符串。因此,在将空内容替换为M_PI
后,表达式
area = M_PI * radius * radius
成为
area = * radius * radius
并且第一个星号成为一元运算符,整个表达式被解释为
area = (* radius) * radius
这个一元星号不能合理地使用double
参数,因此是错误信息。