注:以下两种方法都用到头文件#include<iomanip>
方法一:
使用setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数
setprecision(2)的意思就是小数点输出的精度,即输出小数点右边的数字的个数为2
cout<<fixd<<setprecision(2)<<Sum;//输出一个右对齐的小数点后两位的浮点数
方法二:
C++中的cout.setf()、cout.precision(),ostream成员函数里面的,也可以用输出流操作符来控制;
1. #include<iostream>
2. #include<iomanip>
3. using namespace std;
4. int main() {
5. double a, b, c;
6. float d;
7. a = 3.1415926535;
8. b = 0.3422342344;
9. c = 0.3422302344;
10. d = 1.2321435345;
11. cout << "默认输出" << endl;
12. cout << "a=" << a << endl;
13. cout << "b=" << b << endl;
14. cout << "c=" << c << endl;
15. cout << "d=" << d << endl;
16. //保留小数点后n位小数
17. //方法一
18. cout << fixed;
19. cout << "保留2位小数" << endl;
20. cout << "a=" << setprecision(2) << a << endl;//保留2位小数,3.14
21. cout << "保留3位小数" << endl;
22. cout << "a=" << setprecision(3) << a << endl;//保留3位小数,3.142,四舍五入
23. //或
24. cout << "保留4位小数" << endl;
25. cout << "a=" << fixed << setprecision(4) << a << endl;//保留4位小数,3.1416,四舍五入
26. //方法二
27. /*cout << fixed;*///方法二可以不加这个
28. cout << "保留2位小数" << endl;
29. cout.precision(2);//保留2位小数,可以不加cout<<fixed;
30. cout << "a=" << a << endl;//3.14
31. cout << "b=" << b << endl;//0.34
32. cout << "保留4位小数" << endl;
33. cout.precision(4); //保留3位小数,可以不加cout << fixed;
34. cout << "a=" << a << endl;//3.1416
35. cout << "b=" << b << endl;//0.3422
36. return 0;
}