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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM