C++ 你会使用cmath库里的宏常量吗?(π、e、ln2、√2、(2/√π) 等等)

前面在写定积分函数时,自定义了2个常量:圆周率 π 和 自然常数 e

#define E     2.71828182845904523536
#define Pi    3.14159265358979323846

其实<cmath>或<math.h>库里已经“隐藏”着这些常量了,说它“隐藏”的原因是因为仅包括了库还不能直接引用,必须在"#include <cmath>"之前加一行:

#define _USE_MATH_DEFINES 

注意:是必须哦,必须在<cmath>之前,哪怕就在前一行加就行;另外:如下所示,红色的四个预定义任选一个都行:

#if !defined(__STRICT_ANSI__) || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_USE_MATH_DEFINES)
#define M_E                  2.7182818284590452354
#define M_LOG2E        1.4426950408889634074
#define M_LOG10E      0.43429448190325182765
#define M_LN2              0.69314718055994530942
#define M_LN10            2.30258509299404568402 
#define M_PI                 3.14159265358979323846
#define M_PI_2             1.57079632679489661923
#define M_PI_4             0.78539816339744830962
#define M_1_PI             0.31830988618379067154
#define M_2_PI             0.63661977236758134308
#define M_2_SQRTPI   1.12837916709551257390
#define M_SQRT2        1.41421356237309504880
#define M_SQRT1_2    0.70710678118654752440
#endif

常量的名字中如有第二个“_”,则表示除法,比如: M_PI_2 ==  π/2; M_1_PI == 1/π; M_SQRT1_2 ==  sqrt(1/2) 【1/2的算术平方根,也即 sqrt(2) /2】;M_2_SQRTPI == 2/sqrt(π) 。

测试代码:

#define _USE_MATH_DEFINES 
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cmath>

using namespace std;
 
int main()
{
	stringstream ss;
	ss << setprecision(22) << M_PI;

	cout << ss.str() <<endl;

	cout<< setprecision(22) << M_PI <<endl;

	cout << 3.14159265358979323846 << endl;

	cout << "3.14159265358979323846" << endl << endl;

	ss.str("");
	ss << setprecision(22) << M_E;

	cout << ss.str() <<endl;

	cout<< setprecision(22) << M_E <<endl;

	cout << 2.71828182845904523536 << endl;

	cout << "2.71828182845904523536" << endl;
	
	return 0;
}

精度也只能到小数点后15位,预定义有20位已足够了。

/*
3.141592653589793115998
3.141592653589793115998
3.141592653589793115998
3.14159265358979323846

2.718281828459045090796
2.718281828459045090796
2.718281828459045090796
2.71828182845904523536

--------------------------------
Process exited after 0.5305 seconds with return value 0
请按任意键继续. . .
*/

随后又想到了一个更容易更方便的办法,直接用库函数给常量赋值:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;
 
int main()
{
	const double Pi = acos(-1);  // arccos(-1) = π
	const double E  = exp(1);    // e^1 = e
	
	cout << setprecision(20);
	
	cout << Pi << endl;
	cout << E << endl;
		
	return 0;
}

猜你喜欢

转载自blog.csdn.net/boysoft2002/article/details/114163091