720
720.0
720.00000000
7.2E+ 2
720.0
// This program displays three rows of numbers. #include <iostream> using namespace std; int main() { int num1 = 2897, num2 = 5, num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12; // Display the first row of numbers cout << num1 << " " << num2 << " " << num3 << endl; // Display the second row of numbers cout << num4 << " " << num5 << " " << num6 << endl; // Display the third row of numbers cout << num7 << " " << num8 << " " << num9 << endl; return 0; }程式輸出結果:
2897 5 837
34 7 1623
390 3456 12
value = 23;
cout << setw(5) << value;
value = 23;
cout << "(" << setw(5) << value << ")";
( 23)
請注意,這個數位佔據了欄位的最後兩個位置。由於這個數位沒有使用整個欄位,所以 cout 用空格填充了額外的 3 個位置。因為這個數位出現在欄位的右側,空格“填充”在前面,所以它被認為是右對齊的。// This program uses setw to display three rows of numbers so they align. #include <iostream> #include <iomanip>// Header file needed to use setw using namespace std; int main() { int num1 = 2897, num2 = 5, num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12; // Display the first row of numbers cout << setw(6) << num1 << setw(6) << num2 << setw(6) << num3 << endl; //Display the second row of numbers cout << setw(6) << num4 << setw(6) << num5 << setw(6) << num6 << endl; // Display the third row of numbers cout << setw(6) << num7 << setw(6) << num8 << setw(6) << num9 << endl; return 0; }程式輸出結果:
2897 5 837 34 7 1623 390 3456 12注意,在程式第 3 行的 #include 指令中命名了一個新的標頭檔案 iomanip。該檔案必須包含在使用 setw 的任何程式中。
value = 18397;
cout << setw(2) << value;
// This program demonstrates the setw manipulator //being used with variables of various data types. #include <iostream> #include <iomanip> // Header file needed to use setw #include <string> // Header file needed to use string objects using namespace std; int main() { int intValue = 3928; double doubleValue = 91.5; string stringValue = "Jill Q. Jones"; cout << "(" << setw (5) << intValue << ")" << endl; cout << "(" << setw (8) << doubleValue << ")" << endl; cout << "(" << setw (16) << stringValue << ")" << endl; return 0; }程式輸出結果:
( 3928) ( 91.5) ( Jill Q. Jones)此程式說明了一些要點: