44

当我编译下面的代码时,我收到了这些错误消息:

(Error  1   error C2065: 'M_PI' : undeclared identifier 
2   IntelliSense: identifier "M_PI" is undefined)

这是什么?

#include <iostream>
#include <math.h>

using namespace std;

double my_sqrt1( double n );`enter code here`

int main() {
double k[5] = {-100, -10, -1, 10, 100};
int i;

for ( i = 0; i < 5; i++ ) {
    double val = M_PI * pow( 10.0, k[i] );
    cout << "n: "
         << val
         << "\tmysqrt: "
         << my_sqrt1(val)
         << "\tsqrt: "
         << sqrt(val)
         << endl;
}

return 0;
}

double my_sqrt1( double n ) {
int i;
double x = 1;


for ( i = 0; i < 10; i++ ) {
    x = ( x + n / x ) / 2;
}

return x;
}
4

6 回答 6

93

根据他们的文档,听起来你正在使用 MS 的东西

标准 C/C++ 中未定义数学常量。要使用它们,您必须首先定义 _USE_MATH_DEFINES,然后包含 cmath 或 math.h。

所以你需要类似的东西

#define _USE_MATH_DEFINES
#include <cmath>

作为标题。

于 2014-09-26T17:57:54.457 回答
37

math.h默认情况下不定义M_PI

所以去吧:

#ifndef M_PI
    #define M_PI 3.14159265358979323846
#endif

M_PI这将处理您的标头已定义或未定义的两种情况。

于 2014-09-26T17:48:12.477 回答
12

M_PIGCC 也支持,但你必须做一些工作才能得到它

#undef __STRICT_ANSI__
#include <cmath>

或者,如果您不喜欢污染源文件,请执行

g++ -U__STRICT_ANSI__ <other options>
于 2014-09-26T18:01:58.500 回答
7

正如上面的shep所说,你需要类似的东西

#define _USE_MATH_DEFINES
#include <cmath>

但是,您还包括iostream.

iostream包括很多东西,其中之一最终包括cmath. 这意味着当您将它包含在文件中时,所有符号都已定义,因此当您包含它时它会被有效地忽略并且#define _USE_MATH_DEFINES不起作用

如果你在它cmath之前包含iostream它应该给你更高精度的常量,比如M_PI

#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
于 2019-10-14T14:55:31.413 回答
1

将此包含用于 Windows 10:

#include <corecrt_math_defines.h>
于 2021-11-19T08:37:30.507 回答
0

我在带有远程 linux 主机的 NetBeans 中使用 C99 及其构建工具。
尝试在链接期间添加#define _GNU_SOURCE并添加-lm

于 2019-11-04T16:49:52.327 回答