1. 程式人生 > >C++數字按指定的位數輸出

C++數字按指定的位數輸出

這裡探討C++如何將資料按指定的位數輸出,如將所有列印在螢幕上的資料都按4位數輸出,不夠的前面補0。這裡要用到C++的兩個輸出控制,setw(位數),和setfill(指定字元)。

不講廢話了,見下面程式碼:

#include <iostream>
#include <iomanip>//一定要包含這個c++標頭檔案,非常重要

using namespace std;

int main()
{
	int test[4] = { 1, 12, 123, 1234 };
	for (int i = 0; i < 4; ++i)
	{
		cout << setw(4) << setfill('0') << test[i] << " ";
	}
	cout << endl << endl;
	return 0;
}


輸出結果如下: