我使用的是 Visual Studio 2010.我读到在 C++ 中最好使用
而不是
.
I am using Visual Studio 2010. I have read that in C++ it is better to use <cmath>
rather than <math.h>
.
但是在我尝试编写的程序中(Win32 控制台应用程序,空项目)如果我写:
But in the program I am trying to write (Win32 console application, empty project) if I write:
#define _USE_MATH_DEFINES
#include <math.h>
它编译,而如果我写
#define _USE_MATH_DEFINES
#include <cmath>
它失败了
错误 C2065:'M_PI':未声明的标识符
error C2065: 'M_PI' : undeclared identifier
正常吗?我使用 cmath 还是 math.h 有关系吗?如果是,我怎样才能让它与 cmath 一起工作?
Is it normal? Does it matter if I use cmath or math.h? If yes, how can I make it work with cmath?
UPDATE:如果我在 GUI 中定义 _USE_MATH_DEFINES,它就可以工作.知道为什么会这样吗?
UPDATE: if I define _USE_MATH_DEFINES in the GUI, it works. Any clue why this is happening?
有趣的是,我在我的一个应用上检查了这个,我得到了同样的错误.
Interestingly I checked this on an app of mine and I got the same error.
我花了一段时间检查标题,看看是否有任何未定义的 _USE_MATH_DEFINES
内容,但一无所获.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
所以我移动了
#define _USE_MATH_DEFINES
#include <cmath>
成为我文件中的第一件事(我不使用 PCH,所以如果你是,你必须在 #include "stdafx.h"
之后使用它),突然它完美编译.
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
尝试将其移到页面更高的位置.完全不确定为什么这会导致问题.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
编辑:想通了.#include <math.h>
出现在 cmath 的头文件保护中.这意味着在#includes 列表的更高层包含cmath
,但没有指定#define
.math.h
是专门设计的,因此您可以再次包含它,现在定义更改为添加 M_PI
等.cmath
不是这种情况>.因此,在包含其他任何内容之前,您需要确保 #define _USE_MATH_DEFINES
.希望能帮到你:)
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
如果仅包含 math.h
失败,您将使用非标准 C/C++,正如已经指出的 :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
编辑 2:或者正如大卫在评论中指出的那样,让自己成为一个定义值的常量,并且无论如何你都有更便携的东西:)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)
这篇关于M_PI 适用于 math.h 但不适用于 Visual Studio 中的 cmath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!