在C++的编程中,总会遇到浮点数的处理,有的时候,我们只需要保留2位小数作为输出的结果,这时候,问题来了,怎样才能让cout输出指定的小数点后保留位数呢?
在C语言的编程中,我们可以这样实现它:
printf("%.2f", sample);
在C++中,是没有格式符的,我们可以通过使用setprecision()函数来实现这个需求。
想要使用setprecision()函数,必须包含头文件#include <iomanip>。使用方式如下:
cout << "a=" << setprecision(2) << a <<endl;
这时候,我们会发现,如果a的值为0.20001,输出的结果为a=0.2,后面第二位的0被省略了。
如果我们想要让它自动补0,需要在cout之前进行补0的定义。代码如下:
cout.setf(ios::fixed);
cout << "a=" <<fixed<< setprecision(2) << a <<endl; //输出a=0.20
这样,我们就可以得到0.20了。当然,如果想要关闭掉补0,只需要对fixed进行取消设置操作。
cout.unsetf(ios::fixed);
cout << "a=" << setprecision(2) << a <<endl; //输出a=0.2
参考代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a = 0.20001;
cout.setf(ios::fixed);
cout << "a=" <<fixed<< setprecision(2) << a <<endl; //输出结果为a=0.20
cout.unsetf(ios::fixed);
cout << "a=" << setprecision(2) << a <<endl; //输出结果为a=0.2
return 0;
}
原文地址:https://blog.csdn.net/weixin_39484422/article/details/89072133
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。