C++ 中对浮点数的输出控制

需要用到的东西:

  • 需要用到的库:include<bits/stdc++.h>
  • 需要使用的函数fixed showpoint setprecision(保留个数)//这里的n指保留n位有效数字,包括了小数点前的位数,要想得到小数点后面的个数,需要剪掉小数点前的个数,且小数点后的0,会被舍去

函数解释:

setprecision:功能是控制输出流显示浮点数的有效数字个数(非0数字),必须是输出有效数字,后面的0要省略。

fixed:可以控制小数点后面有几位。即可以解决出现若小数点后仅有0但不显示的情况

showpoint:它允许这些默认值被覆盖。当使用 showpoint 时,表示打印浮点数的小数点和小数位数,即使显示的数值没有小数点

示例:

double x = 456.0;

cout << showpoint << x << endl;

它将显示以下输出结果:

456.000

这里之所以显示了 3 个零,是因为如果没有指定所需的小数点位数,则默认显示 6 个有效数

可以将 fixed、showpoint 和 setprecision 操作符一起使用,以便更好地控制输出的外观

示例如下:

double x = 456.0;

cout << fixed << showpoint << setprecision(2) << x << endl;

此版本的代码产生以下输出:

456.00

下面的程序进一步说明了这些操作符的使用。与 setprecision —样,fixed 和 showpoint 操作符都将持续有效,直到程序员明确更改它们为止:

// This program illustrates the how the showpoint, setprecision, and

// fixed manipulators operate both individually and when used together.

#include <iostream>
#include<bits/stdc++.h>
#include <iomanip> // Header file needed to use stream manipulatorsusing namespace std;
using namespace std;


int main()

{

    double x = 6.0;

    cout << x << endl;

    cout << showpoint << x << endl;

    cout << setprecision(2) << x << endl;

    cout << fixed << x << endl;

    return 0;

}

//程序输出结果:

6

6.00000

6.0

6.00

注意:

但int类型是无法保留小数点的,这里的整数指的是double的整数!

实例:

cout << fixed << showpoint << setprecision(1) << avg << endl;

or

cout << showpoint << setprecision(2) << avg << endl;

or 

cout << fixed  << setprecision(1) << avg << endl;

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值