c++中setprecision函数如何使用

   2025-02-15 4340
核心提示:C++中的setprecision函数用于设置浮点数的精度。其函数原型如下:std::setprecision(int n)其中,n表示要设置的精度位数。要使用

C++中的setprecision函数用于设置浮点数的精度。其函数原型如下:

std::setprecision(int n)

其中,n表示要设置的精度位数。

要使用setprecision函数,需要包含头文件<iomanip>

下面是一个使用setprecision函数的示例代码:

#include <iostream>#include <iomanip>int main() {    double num = 3.14159265359;    std::cout << std::setprecision(4) << num << std::endl;    std::cout << std::setprecision(2) << num << std::endl;    std::cout << std::setprecision(8) << num << std::endl;    return 0;}

输出结果为:

3.1423.13.1415927

可以看到,通过setprecision函数设置了不同的精度位数,输出的浮点数也相应地进行了四舍五入。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言