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

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


当前回答

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

#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+

其他回答

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

我刚刚看到了Danny Kalev写的一篇文章,它为c++ 14及以上版本提供了一个很好的建议。

template<typename T>
constexpr T pi = T(3.1415926535897932385);

我认为这非常酷(尽管我会在其中使用最高精度的PI),特别是因为模板可以基于类型使用它。

template<typename T>
T circular_area(T r) {
  return pi<T> * r * r;
}
double darea= circular_area(5.5);//uses pi<double>
float farea= circular_area(5.5f);//uses pi<float>

我不喜欢#定义,因为它们是零类型安全的简单文本替换。如果省略括号,它们也会在使用表达式时引起问题。

#define T_PI 2*PI

真的应该

#define T_PI (2*PI)

我目前对这个问题的解决方案是使用常量的硬编码值,例如my_constants.hxx

namespace Constants {
    constexpr double PI = 3.141... ;
}

但是我没有硬编码这些值(因为我也不喜欢这种方法),而是使用一个单独的Fortran程序来编写这个文件。我使用Fortran是因为它完全支持四精度(VisualStudio上的c++不支持),三角函数是c++的constexpr等价函数。 如。

real(8), parameter :: pi = 4*atan(1.0d0)

毫无疑问,其他语言也可以用来做同样的事情。

我通常更喜欢自己定义:const double PI = 2*acos(0.0);因为不是所有的实现都为您提供它。

这个函数是在运行时被调用还是在编译时被静态输出的问题通常不是问题,因为它只会发生一次。

#include <cmath>
const long double pi = acos(-1.L);