C/C++保留指定小数位数输出和取整方式

淡淡的烟草味﹌ 2022-11-14 14:39 452阅读 0赞

C++中保留指定位数

步骤:

  1. 包含头文件:#include
  2. cout<<fixed<<setprecision(2);//括号中的数字即保留位数

注意:设置一次后,都按照此精度显示

C语言保留指定位数

%f 格式化输出浮点型数据,在%之后加上“.n”即可。

printf(“%.3f”,1.2356);//保留三位小数显示

以上保留小数,都是按照四舍五入的原则进行的

示例:

取整方式




































函数名称 函数说明 2.1 2.9 -2.1 -2.9
floor() floor,地板,向下取整,不大于自变量的最大整数 2 2 -3 -3
ceil() ceil,天花板,向上取整,不小于自变量的最大整数 3 3 -2 -2
round() 四舍五入到最邻近的整数 2 3 -2 -3
  1. #include <iostream>
  2. #include<stdio.h>
  3. //注意头文件 iomanip
  4. #include<iomanip>
  5. using namespace std;
  6. int main()
  7. {
  8. double pi = 3.5692926123;
  9. cout << "pi = "<< pi << endl;//默认保留五位小数显示
  10. printf("pi = %f\n", pi);//默认保留六位小数显示
  11. printf("保留1位 pi = %.1f\n", pi);
  12. printf("保留2位 pi = %.2f\n", pi);
  13. printf("保留3位 pi = %.3f\n", pi);
  14. // 第一种简便写法
  15. cout << fixed << setprecision(2);
  16. cout << "保留2位 pi = " << pi << endl;
  17. //第二种写法
  18. cout << setiosflags(ios::fixed) << setprecision(3);
  19. cout << "保留3位 pi = " << pi << endl;
  20. //第三种写法
  21. cout.setf(ios::fixed);
  22. cout << setprecision(4);
  23. cout << "保留4位 pi = " << pi << endl;
  24. cout << floor(1.5673456) << endl;
  25. cout << ceil(1.5673456) << endl;
  26. cout << round(1.5673456) << endl;
  27. cout << floor(-1.5673456) << endl;
  28. cout << ceil(-1.5673456) << endl;
  29. cout << round(-1.5673456) << endl;
  30. return 0;
  31. }
  32. /*
  33. pi = 3.56929
  34. pi = 3.569293
  35. 保留1位 pi = 3.6
  36. 保留2位 pi = 3.57
  37. 保留3位 pi = 3.569
  38. 保留2位 pi = 3.57
  39. 保留3位 pi = 3.569
  40. 保留4位 pi = 3.5693
  41. 1.0000
  42. 2.0000
  43. 2.0000
  44. -2.0000
  45. -1.0000
  46. -2.0000
  47. */

发表评论

表情:
评论列表 (有 0 条评论,452人围观)

还没有评论,来说两句吧...

相关阅读

    相关 小数方式

    Math类中提供了5个与取整相关的函数,如下所示: static double ceil(double a); //天花板函数,返回大于等于a的最小整数(但是

    相关 mysql 小数

    sum()计算结果取整,怎么写? 包含头文件\include 向下取整可以用floor(),向上取整用ceil(),就行了啊,看你想要哪种了 ![mysql 小数取整