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

您所在的位置:网站首页 π是常量吗 C++ 你会使用cmath库里的宏常量吗?(π、e、ln2、√2、(2/√π) 等等)

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

2023-11-19 22:59| 来源: 网络整理| 查看: 265

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

#define E     2.71828182845904523536 #define Pi    3.14159265358979323846

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

#define _USE_MATH_DEFINES 

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

#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 #include #include #include #include using namespace std; int main() { stringstream ss; ss


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3