C++使用fixed和precision控制小數和有效位數的輸出以及setw()設置輸出寬度


頭文件iomanip中包含了setiosflags與setprecision,也可以用fixed 代替setiosflags(ios::fixed)

#include<iostream>//fixed
#include<iomanip>//包含setiosflags與setprecision
using namespace std;
int main()
{
	//fixed控制小數,precision控制有效位數
	double a = 123.6666;
	printf("%.2f\n", a); //保留兩位小數,輸出123.67
 
	cout << a << endl;   //默認情況下,保留六位有效數字,輸出123.667
 
	cout.setf(ios::fixed); //控制小數
	cout << a << endl;   //保留六位小數,輸出123.666600
 
	cout.precision(1);    //控制保留位數
	cout << a << endl;   //保留一位小數,輸出123.7
 
	cout.unsetf(ios::fixed);
 
	cout << a << endl;   //保留一位有效數字,輸出1e+02
 
	cout << setprecision(2) << a << endl;   //保留兩位有效數字,輸出1.2e+02
	cout << setiosflags(ios::fixed) <<setprecision(2) << a << endl;//保留兩位小數,輸出123.67
	cout << fixed << setprecision(2) << a << endl;  //同上
}

  

output:

123.67
123.667
123.666600
123.7
1e+002
1.2e+002
123.67
123.67

  

使用setw(n)設置輸出寬度時,默認為右對齊,如下:

std::cout << std::setw(5) << "1" << std::endl;
std::cout << std::setw(5) << "10" << std::endl;
std::cout << std::setw(5) << "100" << std::endl;
std::cout << std::setw(5) << "1000" << std::endl;

輸出結果:

    1
   10
  100
 1000

若想讓它左對齊的話,只需要插入 std::left,如下:

std::cout << std::left << std::setw(5) << "1" << std::endl;
std::cout << std::left << std::setw(5) << "10" << std::endl;
std::cout << std::left << std::setw(5) << "100" << std::endl;
std::cout << std::left << std::setw(5) << "1000" << std::endl;

輸出結果:

1
10
100
1000

同理,右對齊只要插入 std::right,不過右對齊是默認狀態,不必顯式聲明。 


免責聲明!

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



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