cout输出精度:如何输出小数点后指定位数

buyan2009 2009-11-18 06:42:12
如何输出小数点后指定位数
...全文
15311 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
一灯 2011-09-29
  • 打赏
  • 举报
回复
mark
大道曙光 2011-09-22
  • 打赏
  • 举报
回复
mark
frogoscar 2011-06-28
  • 打赏
  • 举报
回复
up up study ~~~~~~~~~~~~
buyan2009 2009-11-18
  • 打赏
  • 举报
回复
Thank you all very much!
clhposs 2009-11-18
  • 打赏
  • 举报
回复
setprecision(n)设置精度为n,

当没有设置fixed时,这个数的精度为n,设置fixed时,小数点后的数字精度为n,小数点前没有限制。
老邓 2009-11-18
  • 打赏
  • 举报
回复
/*关于浮点数的格式*/  
#include <iostream.h>
void main()
{
float f=2.0/3.0,f1=0.000000001,f2=-9.9;
cout<<f<<' '<<f1<<' '<<f2<<endl; //正常输出
cout.setf(ios::showpos); //强制在正数前加+号
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout.unsetf(ios::showpos); //取消正数前加+号
cout.setf(ios::showpoint); //强制显示小数点后的无效0
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout.unsetf(ios::showpoint); //取消显示小数点后的无效0
cout.setf(ios::scientific); //科学记数法
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout.unsetf(ios::scientific); //取消科学记数法
cout.setf(ios::fixed); //按点输出显示
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout.unsetf(ios::fixed); //取消按点输出显示
cout.precision(18); //精度为18,正常为6
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout.precision(6); //精度恢复为6
}
操纵算子:
/*关于浮点数的格式*/
#include <iomanip.h>
void main()
{
float f=2.0/3.0,f1=0.000000001,f2=-9.9;
cout<<f<<' '<<f1<<' '<<f2<<endl; //正常输出
cout<<setiosflags(ios::showpos); //强制在正数前加+号
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout<<resetiosflags(ios::showpos); //取消正数前加+号
cout<<setiosflags(ios::showpoint); //强制显示小数点后的无效0
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout<<resetiosflags(ios::showpoint); //取消显示小数点后的无效0
cout<<setiosflags(ios::scientific); //科学记数法
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout<<resetiosflags(ios::scientific); //取消科学记数法
cout<<setiosflags(ios::fixed); //按点输出显示
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout<<resetiosflags(ios::fixed); //取消按点输出显示
cout<<setprecision(18); //精度为18,正常为6
cout<<f<<' '<<f1<<' '<<f2<<endl;
cout<<setprecision(6); //精度恢复为6
}
老邓 2009-11-18
  • 打赏
  • 举报
回复
#include <iostream.h>   
#include <iomanip.h>
void main(void)
{
cout.setf(ios::fixed);
cout<<setprecision(2)<<(float)0.1<<endl;//输出0.10
cout.unsetf(ios::fixed);
cout<<setprecision(2)<<(float)0.1<<endl; //输出0.1
}
clhposs 2009-11-18
  • 打赏
  • 举报
回复
C++ primer 最后面有讲解
王旺旺旺 2009-11-18
  • 打赏
  • 举报
回复
好像有个setp……什么的函数。
你看看介绍C++标准库的format相关章节。

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧