#include <iostream> #include <cmath> // 包含数学函数 int main(){ double num =9.0; double root =sqrt(num);// 计算平方根 double power =pow(2.0, 3.0);// 计算 2 的 3 次幂
std::cout<<"The square root of "<< num <<" is "<< root << std::endl; std::cout<<"The power of 2 to the 3 is "<< power << std::endl; return0; }
输出结果:
The square root of 9is3The power of 2 to the 3is8
注意事项
浮点数的精度是有限的,因此在进行浮点数运算时可能会遇到精度问题。
在比较两个浮点数是否相等时,应该使用一个小的误差范围来判断,而不是直接使用 ==
操作符。
虽然 "cfloat" 不是 C++
标准库的一部分,但 C++ 提供了强大的浮点数支持和相关的数学函数库。通过使用 <cmath>
头文件,你可以方便地进行各种浮点数运算。希望这篇文章能帮助初学者更好地理解 C++ 中的浮点数操作。