找回密码
 中文实名注册
查看: 210|回复: 0

c++ setprecision用法详解

[复制链接]

694

主题

1082

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
22801
发表于 2022-3-15 08:20:09 | 显示全部楼层 |阅读模式
浮点值可以四舍五入到若干位有效数或精度,这是出现在小数点前后的总位数。可以通过使用 setprecision 操作符来控制显示浮点数值的有效数的数量。

下面的程序显示了用不同数量的有效数来显示除法运算的结果:
[C++] 纯文本查看 复制代码
// This program demonstrates how the setprecision manipulator
// affects the way a floating-point value is displayed.
#include <iostream>
#include <iomanip> // Header file needed to use setprecision
using namespace std;
int main()
{
    double number1 = 132.364, number2 = 26.91;
    double quotient = number1 / number2;
    cout << quotient << endl;
    cout << setprecision(5) << quotient << endl;
    cout << setprecision(4) << quotient << endl;
    cout << setprecision(3) << quotient << endl;
    cout << setprecision(2) << quotient << endl;
    cout << setprecision(1) << quotient << endl;
    return 0;
}


程序输出结果:
4.91877
4.9188
4.919
4.92
4.9
5
注意,使用预标准编译器输出的结果可能与此结果不同。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

小黑屋|东台市机器人学会 ( 苏ICP备2021035350号-1;苏ICP备2021035350号-2;苏ICP备2021035350号-3 )

GMT+8, 2024-4-30 02:50 , Processed in 0.045630 second(s), 28 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表