世界上只有一种英雄主义,就是在看了生活的真相之后|

*Sakura/*

园龄:5年6个月粉丝:2关注:2

C++保留任意小数点位数,小数点后,四舍五入,格式化输出

1.保留有效数字问题

复制代码
#include<iostream>
#include<iomanip>
#include "stdlib.h"
using namespace std;
int main(){
  double PI=3.1415926;
  cout<<setprecision(3)<<PI<<endl;
  system("pause");
  return 0;//3.14
}
复制代码

 

2.保留小数点后几位问题

上例中定义的PI小数点后有数位,可以保留小数点后两位(三位有效数字)。如果double a=100;再按上述方法输出a,则只会输出100,并不是小数.那么该怎么解决这个问题呢?只需添加setiosflags(ios::fixed)即可,看代码。

复制代码
#include<iostream>
#include<iomanip>
#include "stdlib.h"
using namespace std;
int main(){
//double PI=3.1415926;
  double a=100;
  cout<<setiosflags(ios::fixed)<<setprecision(3)<<a<<endl;
  return 0; //100.000
}
复制代码

 

3.格式化输出

当你输出时间格式的时候需要酱紫的输出(01:08:31)作为结果,然而你的输出却是酱紫:1:8:31,What should I do?这时候就需要C++的格式化输出了。

复制代码
#include "stdlib.h"
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
  int a=1;
  cout.setf(ios::right);
  cout.fill('0');
  cout.width(2);
  cout<<a<<endl;;
  return 0;//01
}
复制代码

 

参考:https://blog.csdn.net/Richard__Ting/article/details/80375870

 

本文作者:杰哥的博客

本文链接:https://www.cnblogs.com/xioazhenblogs/p/12371693.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   *Sakura/*  阅读(3645)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起