// 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 Figures\n"; 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 个字符的字段宽度右对齐打印。
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有