我想在一些C ++程序中使用PI常量和三角函数。 我获得了include <math.h>
的三角函数。 可是,此头文件中彷佛没有PI的定义。 缓存
如何在不手动定义PI的状况下获取PI? ide
The <math.h> header shall provide for the following constants. The values are of type double and are accurate within the precision of the double type. M_PI Value of pi M_PI_2 Value of pi/2 M_PI_4 Value of pi/4 M_1_PI Value of 1/pi M_2_PI Value of 2/pi M_2_SQRTPI Value of 2/ sqrt pi
Pi能够按atan(1)*4
。 你能够用这种方式计算值并缓存它。 spa
标准C ++没有PI的常量。 code
许多C ++编译器定义M_PI
在cmath
(或在math.h
为C)做为非标准扩展。 您可能必须先#define _USE_MATH_DEFINES
才能看到它。 ci
在某些(特别是较旧的)平台上(请参阅下面的评论),您可能须要这样作 get
#define _USE_MATH_DEFINES
而后包含必要的头文件: 编译器
#include <math.h>
pi的值能够经过如下方式访问: 数学
M_PI
在个人math.h
(2014)中,它被定义为: it
# define M_PI 3.14159265358979323846 /* pi */
但请查看math.h
了解更多信息。 来自“旧” 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. */
然而:
在较新的平台上(至少在个人64位Ubuntu 14.04上)我不须要定义_USE_MATH_DEFINES
在(最近的)Linux平台上,做为GNU扩展提供了long double
值:
# define M_PIl 3.141592653589793238462643383279502884L /* pi */
因为官方标准库没有定义常量PI,所以您必须本身定义它。 因此你的问题的答案是“如何在不手动定义PI的状况下得到PI?” 是“你没有 - 或者你依赖于一些特定于编译器的扩展。” 若是您不关心可移植性,能够查看编译器的手册。
C ++容许你写
const double PI = std::atan(1.0)*4;
可是这个常量的初始化并不保证是静态的。 然而,G ++编译器将这些数学函数做为内在函数处理,而且可以在编译时计算此常量表达式。