我想在一些c++程序中使用PI常数和三角函数。我得到三角函数包含<math。h>。然而,在这个头文件中似乎没有PI的定义。

如何获得PI而不手动定义它?


当前回答

而是从芯片上的FPU单元获取:

double get_PI()
{
    double pi;
    __asm
    {
        fldpi
        fstp pi
    }
    return pi;
}

double PI = get_PI();

其他回答

小数点后15位让人类到达月球表面并返回。任何超出这个范围的都是天文数字。你能在一个更小的尺度上测量这个吗?其他人则花了几个月的时间计算到数万亿位数。除了记录在案之外,这没什么用。

要知道你可以把圆周率计算到任意长度,但keep是实用的。

Pi可计算为atan(1)*4。您可以这样计算值并缓存它。

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

#define _USE_MATH_DEFINES

然后包含必要的头文件:

#include <math.h>

PI的值可以通过:

M_PI

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

# 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_definitions 在(最近的)Linux平台上,GNU扩展也提供了长double值: #定义M_PIl 3.141592653589793238462643383279502884L /* pi */

来自math.h的Posix手册页:

   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

你可以用它:

#define _USE_MATH_DEFINES // for C++
#include <cmath>

#define _USE_MATH_DEFINES // for C
#include <math.h>

在标准C/ c++中没有定义数学常数。要使用它们,必须首先定义_use_math_definitions,然后包括cmath或math.h。