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

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


当前回答

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

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

double PI = get_PI();

其他回答

在c++ 20标准库中,π被定义为std::numbers::pi_v,用于浮点数、双精度数和长双精度数。

#include <numbers>
auto n = std::numbers::pi_v<float>;

并且可以专门化为用户定义的类型。

你可以这样做:

#include <cmath>
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif

如果M_PI已经在cmath中定义,那么除了包含cmath之外,它不会做任何其他事情。如果M_PI没有定义(在Visual Studio中就是这种情况),它会定义它。在这两种情况下,都可以使用M_PI来获取pi的值。

这个圆周率值来自Qt Creator的qmath.h。

我在项目中使用了一个覆盖所有基础的公共头文件:

#define _USE_MATH_DEFINES
#include <cmath>

#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif

#ifndef M_PIl
#define M_PIl (3.14159265358979323846264338327950288)
#endif

另外,如果包含<cmath>,下面所有的编译器都定义了M_PI和M_PIl常量。不需要添加只有vc++才需要的#define _use_math_definitions。

x86 GCC 4.4+
ARM GCC 4.5+
x86 Clang 3.0+

我建议你只输入你需要的精度。这不会为您的执行增加计算时间,并且无需使用任何头文件或#define即可移植。计算acos或atan总是比使用预先计算的值更昂贵。

const double PI  =3.141592653589793238463;
const float  PI_F=3.14159265358979f;

来自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