// This program demonstrates how the setprecision manipulator // affects the way a floating-point value is displayed. #include <iostream> #include <iomanip> // Header file needed to use setprecision using namespace std; int main() { double number1 = 132.364, number2 = 26.91; double quotient = number1 / number2; cout << quotient << endl; cout << setprecision(5) << quotient << endl; cout << setprecision(4) << quotient << endl; cout << setprecision(3) << quotient << endl; cout << setprecision(2) << quotient << endl; cout << setprecision(1) << quotient << endl; return 0; }程式輸出結果:
4.91877
4.9188
4.919
4.92
4.9
5
double dollars = 24.51;
cout << dollars << endl; // 顯示 24.51
cout << setprecision (5) << dollars << endl; // 顯示 24.51
數 字 | 操作符 | 顯示的值 |
---|---|---|
28.92786 | setprecision(3) | 28.9 |
21.40 | setprecision(5) | 21.4 |
109.50 | setprecision(4) | 109.5 |
34.78596 | setprecision(2) | 35 |
// This program asks for sales figures for three days. // The total sales are calculated and displayed in a table. #include <iostream> #include <iomanip> // Header file needed to use stream manipulators using namespace std; int main() { double day1, day2, day3, total; // Get the sales for each day cout << "Enter the sales for day 1: "; cin >> dayl; cout << "Enter the sales for day 2: ”; cin >> day2; cout << "Enter the sales for day 3: ”; cin >> day3; // Calculate total sales total = day1 + day2 + day3; // Display the sales figures cout << "nSales Figuresn"; cout << "-------------n" ; cout << setprecision (5); cout << "Day 1: " << setw(8) << day1 << endl; cout << "Day 2: " << setw(8) << day2 << endl; cout << "Day 3: " << setw(8) << day3 << endl; cout << "Total: " << setw(8) << total << endl; return 0; }程式輸出結果:
Enter the sales ;for day 1: 321.57 Enter the sales for day 2: 269,60 Enter the sales for day 3: 307.00 Sales Figures ------------- Day 1: 321.57 Day 2: 269.6 Day 3: 307 Total: 898.17該程式建立的輸出,按照指示,允許顯示最多 5 個有效數,並以 8 個字元的欄位寬度右對齊列印。