当前位置:   article > 正文

c++ 数值计算<cmath>头文件介绍

c++ 数值计算<cmath>头文件介绍

<cmath> 是 C++ 标准库中的头文件,它提供了一系列数学函数和常量,用于执行各种数学计算。在 C++ 中,<cmath> 头文件中定义的函数和常量都位于 std 命名空间中。

以下是 <cmath> 头文件中常用的一些函数和常量:

常用数学函数:

  1. 三角函数:

    • sin, cos, tan:求正弦、余弦、正切值。
    • asin, acos, atan:求反正弦、反余弦、反正切值。
    • atan2:求两个参数的反正切值。
  2. 双曲函数:

    • sinh, cosh, tanh:求双曲正弦、双曲余弦、双曲正切值。
    • asinh, acosh, atanh:求反双曲正弦、反双曲余弦、反双曲正切值。
  3. 指数和对数函数:

    • exp, log, log10:求指数、自然对数、常用对数。
    • log2:求以2为底的对数。
    • pow:求幂函数。
  4. 取整函数:

    • ceil:向上取整。
    • floor:向下取整。
    • round:四舍五入取整。
  5. 其他函数:

    • sqrt:求平方根。
    • fabs:求绝对值。
    • fmod:求浮点数取模。

常用数学常量:

  • M_PI:π(圆周率)。
  • M_E:e(自然对数的底)。

除了上述函数和常量,<cmath> 还包含了其他一些数学函数和常量,可根据具体需求进行查阅和使用。这些函数和常量能够帮助你在 C++ 中进行各种数学计算。

  1. #include <iostream>
  2. #include <cmath>
  3. int main() {
  4. // 计算平方根
  5. double x = 16.0;
  6. double squareRoot = std::sqrt(x);
  7. std::cout << "Square root of " << x << " is: " << squareRoot << std::endl;
  8. // 计算正弦值
  9. double angle = 45.0; // 角度
  10. double radians = angle * M_PI / 180.0; // 将角度转换为弧度
  11. double sineValue = std::sin(radians);
  12. std::cout << "Sine of " << angle << " degrees is: " << sineValue << std::endl;
  13. // 计算自然对数
  14. double num = 2.0;
  15. double naturalLog = std::log(num);
  16. std::cout << "Natural logarithm of " << num << " is: " << naturalLog << std::endl;
  17. // 计算指数
  18. double base = 2.0;
  19. double exponent = 3.0;
  20. double result = std::pow(base, exponent);
  21. std::cout << base << " raised to the power of " << exponent << " is: " << result << std::endl;
  22. // 向上取整
  23. double y = 4.3;
  24. double ceilValue = std::ceil(y);
  25. std::cout << "Ceil value of " << y << " is: " << ceilValue << std::endl;
  26. return 0;
  27. }

参考:

https://en.cppreference.com/w/cpp/header/cmath

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/372605
推荐阅读
相关标签
  

闽ICP备14008679号