C++ M_PI 标记为未声明的标识符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26065359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
M_PI flagged as undeclared identifier
提问by Eunsu Kim
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;
}
回答by Shep
It sounds like you're using MS stuff, according to their docs
根据他们的文档,听起来您正在使用 MS 的东西
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_DEFINES,然后包含 cmath 或 math.h。
So you need something like
所以你需要类似的东西
#define _USE_MATH_DEFINES
#include <cmath>
as a header.
作为标题。
回答by Hemant Gangwar
math.h
does not define M_PI
by default.
math.h
M_PI
默认不定义。
So go with this:
所以用这个:
#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
定义或未定义的两种情况。
回答by legends2k
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>
回答by Metric Crapton
As noted by shep above you need something like
正如上面shep所指出的,你需要类似的东西
#define _USE_MATH_DEFINES
#include <cmath>
However you also include iostream
.
但是,您还包括iostream
.
iostream
includes a lot of stuff and one of those things eventually includes cmath
. This means that by the time you include it in your file all the symbols have already been defined so it is effectively ignored when you include it and the #define _USE_MATH_DEFINES
doesn't work
iostream
包括很多东西,其中一项最终包括cmath
. 这意味着当您将它包含在文件中时,所有符号都已定义,因此当您包含它时它会被有效地忽略并且#define _USE_MATH_DEFINES
不起作用
If you include cmath
before iostream
it should give you the higher precision constants like M_PI
如果你cmath
在iostream
它之前包含它应该给你更高精度的常量,比如M_PI
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
回答by Eruthon
I used C99 in NetBeans with remote linux host with its build tools.
Try adding #define _GNU_SOURCE
and add the -lm
during linking.
我在 NetBeans 中使用 C99 和远程 linux 主机及其构建工具。
尝试在链接期间添加#define _GNU_SOURCE
和添加-lm
。