M_PI flagged as undeclared identifier

Eunsu Kim picture Eunsu Kim · Sep 26, 2014 · Viewed 75.4k times · Source

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

Answer

Shep picture Shep · Sep 26, 2014

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.

So you need something like

#define _USE_MATH_DEFINES
#include <cmath>

as a header.