c++ setprecision用法详解

c++ setprecision用法详解

可以通过使用 setprecision 操作符来控制显示浮点数值的有效数字的数量。

#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

请注意,如果有效数少于要显示的数字,则 setprecision 将舍入,而不是截断数字。另外还需要注意的是,末尾的零将被省略。因此,尽管指定了 setprecision(5),但是 21.40 仍显示为 21.4。
setw 可以设置字段宽度。

// This program asks for sales figures for three days.
// The total sales are calculated and displayed in a table.
#include <iostream>
#include <iomanip> // Header file needed to use stream manipulators
using namespace std;

int main()
{
    double day1, day2, day3, total;
    // Get the sales for each day
    cout << "Enter the sales for day 1: ";
    cin >> dayl;
    cout << "Enter the sales for day 2:;
    cin >> day2;
    cout << "Enter the sales for day 3:;
    cin >> day3;
    // Calculate total sales
    total = day1 + day2 + day3;
    // Display the sales figures
    cout << "\nSales Figures\n";
    cout << "-------------\n" ;
    cout << setprecision (5);
    cout << "Day 1: " << setw(8) << day1 << endl;
    cout << "Day 2: " << setw(8) << day2 << endl;
    cout << "Day 3: " << setw(8) << day3 << endl;
    cout << "Total: " << setw(8) << total << endl;
    return 0;
}

程序输出结果:

Enter the sales ;for day 1: 321.57 
Enter the sales for day 2: 269,60
Enter the sales for day 3: 307.00
Sales Figures
-------------
Day 1:   321.57
Day 2:    269.6
Day 3:      307
Total:   898.17

该程序创建的输出,按照指示,允许显示最多 5 个有效数,并以 8 个字符的字段宽度右对齐打印。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值