
下面的程序显示了用不同数量的有效数来显示除法运算的结果:
// 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 setprecisionusing 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
程序中的第一个值显示在第 11 行,没有设置 setprecision *** 作符(默认情况下,系统使用 6 个有效数显示浮点值)。后续的 cout 语句打印相同的值,但四舍五入为 5、4、3、2 和 1 个有效数。
请注意,与 setw 不同的是,setprecision 不计算小数点。例如,当使用 setprecision(5) 时,输出包含 5 位有效数,但是需要 6 个位置来显示 4.9188。
如果一个数字的值可以由少于 setprecision 指定的精度位数来表示,则 *** 作符将不起作用。在以下语句中,dollars 的值只有 4 位数字,所以 2 个 cout 语句显示的数字都是 24.51:
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 |
与 setw 字段宽度不同的是,setprecision 的精度设置将保持有效,直到更改为其他值为止。与所有格式化 *** 作符一样,必须包含头文件 iomanip 才能使用 setprecision。
下面的程序显示了如何组合使用 setw 和 setprecision *** 作符来控制显示浮点数的方式。
// 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 manipulatorsusing 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,60Enter the sales for day 3: 307.00Sales figures-------------Day 1: 321.57Day 2: 269.6Day 3: 307Total: 898.17该程序创建的输出,按照指示,允许显示最多 5 个有效数,并以 8 个字符的字段宽度右对齐打印。 总结
以上是内存溢出为你收集整理的c++ setprecision用法详解全部内容,希望文章能够帮你解决c++ setprecision用法详解所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)