M_PI标记为未声明的标识符。

时间:2021-07-09 07:23:17

When I compile the code below, I got these error messages:

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

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

What is this?

这是什么?

#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;
}

3 个解决方案

#1


42  

It sounds like you're using MS stuff, according to their docs

据他们的医生说,听起来好像你在用微软的东西。

Math Constants are not defined in Standard C/C++. To use them, you must first define _USE_MATH_DEFINES and then include cmath or math.h.

在标准C/ c++中没有定义数学常数。要使用它们,首先必须定义_use_math_define,然后包括cmath或math.h。

So you need something like

所以你需要一些类似的东西。

#define _USE_MATH_DEFINES
#include <cmath>

as a header.

作为一个头。

#2


14  

math.h not defines M_PI by default. So go with this:

数学。默认情况下,h不定义M_PI。所以用这个:

#ifndef M_PI
    #define M_PI 3.14159265358979323846
#endif

This will handle both cases either your header have M_PI defined or not.

这将处理两种情况,要么你的头有M_PI定义。

#3


2  

M_PI is supported by GCC too, but you've to do some work to get it

M_PI也得到GCC的支持,但是您必须做一些工作来获得它。

#undef __STRICT_ANSI__
#include <cmath>

or if you don't like to pollute your source file, then do

或者如果你不喜欢污染你的源文件,那就去吧。

g++ -U__STRICT_ANSI__ <other options>

#1


42  

It sounds like you're using MS stuff, according to their docs

据他们的医生说,听起来好像你在用微软的东西。

Math Constants are not defined in Standard C/C++. To use them, you must first define _USE_MATH_DEFINES and then include cmath or math.h.

在标准C/ c++中没有定义数学常数。要使用它们,首先必须定义_use_math_define,然后包括cmath或math.h。

So you need something like

所以你需要一些类似的东西。

#define _USE_MATH_DEFINES
#include <cmath>

as a header.

作为一个头。

#2


14  

math.h not defines M_PI by default. So go with this:

数学。默认情况下,h不定义M_PI。所以用这个:

#ifndef M_PI
    #define M_PI 3.14159265358979323846
#endif

This will handle both cases either your header have M_PI defined or not.

这将处理两种情况,要么你的头有M_PI定义。

#3


2  

M_PI is supported by GCC too, but you've to do some work to get it

M_PI也得到GCC的支持,但是您必须做一些工作来获得它。

#undef __STRICT_ANSI__
#include <cmath>

or if you don't like to pollute your source file, then do

或者如果你不喜欢污染你的源文件,那就去吧。

g++ -U__STRICT_ANSI__ <other options>