c++ 格式化输出、保留相应小数位数 学习记录

来源:https://www.bilibili.com/video/BV12x411D7xr?p=127

在我的vs2019中执行以下代码:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	double a = sin(1)*1000;
	double b = 1.0;
	cout << a<<endl;
	cout << fixed << a << endl;
	cout << b << endl;
	return 0;
}

输出:
在这里插入图片描述
可见cout对double型的数据默认输出6位有效数字,当使用fixed后会把之后的输入流固定输出小数点后六位的数字。
同时fix的还会把科学计数法的输出格式转化为非科学计数法的输出
在这里插入图片描述
在这里插入图片描述

如果想要自定义输出精度的话可以使用setprecition,使用时要#include

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
	double a = sin(1)*1000;
	double b = 1.0;
	double c = a * 1000000;
	cout << a << endl;
	cout << setprecision(10) << a << endl;
	cout << c << endl;
	return 0;
}

在这里插入图片描述
发现第二行并没有输出小数点后十位,同时第三行小数点后甚至只有一位,因为setprecision(10)输出的是十位有效数字
更改一下,加上fixed就可以了,如下:

	double a = sin(1)*1000;
	double b = 1.0;
	double c = a * 1000000;
	cout << a << endl;
	cout << setprecision(10) << a << endl;
	cout <<fixed<< setprecision(10) << a << endl;
	cout << c << endl;

在这里插入图片描述
需要注意的是如果要超出double类型精度范围的小数位数,超出的部分会不准确

	double a = 10000 / 3.0;
	cout << fixed << setprecision(20) << a << endl;

输出:
在这里插入图片描述

另外使用setw()可以控制输出的数字,字符的宽度:
right 右对齐,left 左对齐

int a = 1, b = 1000000;
cout << right << setw(3) << a << endl;
cout << left << setw(3) << a << endl;
cout << setw(3) << b << endl;

在这里插入图片描述

setfill()可以填充字符的宽度

	int a = 1, b = 1000000;
	cout << setfill('*');
	cout << right << setw(3) << a << endl;
	cout << left << setw(3) << a << endl;
	cout << setw(3) << b << endl;

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值