欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

c++ 保留有效数字、小数和格式化输出

最编程 2024-04-23 08:51:52
...

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;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

保留三位有效数字 
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;
    system("pause");
    return 0;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

保留小数点后几位 
这样输出便不再是保留有效数字了,而是保留的小数点后的位数。 
3、格式化输出(01) 
当你输出时间格式的时候需要酱紫的输出(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;;
    system("pause");
    return 0;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

运行结果 


转载自:http://blog.****.net/RayKevin/article/details/53152154