我想在一些c++程序中使用PI常数和三角函数。我得到三角函数包含<math。h>。然而,在这个头文件中似乎没有PI的定义。
如何获得PI而不手动定义它?
我想在一些c++程序中使用PI常数和三角函数。我得到三角函数包含<math。h>。然而,在这个头文件中似乎没有PI的定义。
如何获得PI而不手动定义它?
当前回答
而不是写作
#define _USE_MATH_DEFINES
我建议使用- use_math_definitions或/ d_use_math_definitions,这取决于你的编译器。
通过这种方式,即使有人在您之前包含了头文件(并且没有使用#define),您仍然可以得到常量,而不是一个晦涩的编译器错误,您需要花费很长时间来查找。
其他回答
你也可以使用boost,它为所请求的类型定义了最精确的重要数学常数(例如float vs double)。
const double pi = boost::math::constants::pi<double>();
查看boost文档以获得更多示例。
我建议你只输入你需要的精度。这不会为您的执行增加计算时间,并且无需使用任何头文件或#define即可移植。计算acos或atan总是比使用预先计算的值更昂贵。
const double PI =3.141592653589793238463;
const float PI_F=3.14159265358979f;
#include <cmath>
const long double pi = acos(-1.L);
来自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。