問題描述
我使用的是 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模板網!