// 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: 145678.99
Enter the sales for day 2: 205614.85
Enter the sales for day 3: 198645.22
Sales Figures
-------------
Day 1: 1.4568e+005
Day 2: 2.0561e+005
Day 3: 1.9865e+005
Total: 5.4994e+005
cout << fixed;
當然,fixed 操作符可能最重要的還是當它與 setprecision 操作符一起使用時,setprecision 即可以以一種新的方式顯示。它將指定浮點數位的小數點後要顯示的位數,而不是要顯示的總有效數位數。而這通常正是我們想要的。cout << fixed << setprecision(2);
然後使用相同的樣本資料重新執行程式,即可得到以下結果: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.60 Day 3: 307.00 Total: 898.17通過將 fixed 和 setprecision 結合起來使用,得到了所需的輸出結果。請注意,在這種情況下,精度值應設定為 2,這是希望看到的小數位數,而不是 5。