Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c++ - 如何在C ++中使用PI常量(How to use the PI constant in C++)

I want to use the PI constant and trigonometric functions in some C++ program.

(我想在一些C ++程序中使用PI常量和三角函数。)

I get the trigonometric functions with include <math.h> .

(我得到了include <math.h>的三角函数。)

However, there doesn't seem to be a definition for PI in this header file.

(但是,此头文件中似乎没有PI的定义。)

How can I get PI without defining it manually?

(如何在不手动定义PI的情况下获取PI?)

  ask by Etan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On some (especially older) platforms (see the comments below) you might need to

(在某些(特别是较旧的)平台上(请参阅下面的评论),您可能需要这样做)

#define _USE_MATH_DEFINES

and then include the necessary header file:

(然后包含必要的头文件:)

#include <math.h>

and the value of pi can be accessed via:

(pi的值可以通过以下方式访问:)

M_PI

In my math.h (2014) it is defined as:

(在我的math.h (2014)中,它被定义为:)

# define M_PI           3.14159265358979323846  /* pi */

but check your math.h for more.

(但请查看math.h了解更多信息。)

An extract from the "old" math.h (in 2009):

(来自“旧” math.h的摘录(2009年):)

/* Define _USE_MATH_DEFINES before including math.h to expose these macro
 * definitions for common math constants.  These are placed under an #ifdef
 * since these commonly-defined names are not part of the C/C++ standards.
 */

However:

(然而:)

  1. on newer platforms (at least on my 64 bit Ubuntu 14.04) I do not need to define the _USE_MATH_DEFINES

    (在较新的平台上(至少在我的64位Ubuntu 14.04上)我不需要定义_USE_MATH_DEFINES)

  2. On (recent) Linux platforms there are long double values too provided as a GNU Extension:

    (在(最近的)Linux平台上,作为GNU扩展提供了long double值:)

     # define M_PIl 3.141592653589793238462643383279502884L /* pi */ 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...