zoukankan      html  css  js  c++  java
  • c++小数点后舍入

    c++ math.h中有这么几种函数:round,floor,ceil,trunc

    round提供四舍五入,floor向下取整,ceil向上取整,trunc截断

    例子 

    /* round vs floor vs ceil vs trunc */
    #include <stdio.h>      /* printf */
    #include <math.h>       /* round, floor, ceil, trunc */
    
    int main ()
    {
      const char * format = "%.1f 	%.1f 	%.1f 	%.1f 	%.1f
    ";
      printf ("value	round	floor	ceil	trunc
    ");
      printf ("-----	-----	-----	----	-----
    ");
      printf (format, 2.3,round( 2.3),floor( 2.3),ceil( 2.3),trunc( 2.3));
      printf (format, 3.8,round( 3.8),floor( 3.8),ceil( 3.8),trunc( 3.8));
      printf (format, 5.5,round( 5.5),floor( 5.5),ceil( 5.5),trunc( 5.5));
      printf (format,-2.3,round(-2.3),floor(-2.3),ceil(-2.3),trunc(-2.3));
      printf (format,-3.8,round(-3.8),floor(-3.8),ceil(-3.8),trunc(-3.8));
      printf (format,-5.5,round(-5.5),floor(-5.5),ceil(-5.5),trunc(-5.5));
      return 0;
    }

    Output:

    value   round   floor   ceil    trunc
    -----   -----   -----   ----    -----
    2.3     2.0     2.0     3.0     2.0
    3.8     4.0     3.0     4.0     3.0
    5.5     6.0     5.0     6.0     5.0
    -2.3    -2.0    -3.0    -2.0    -2.0
    -3.8    -4.0    -4.0    -3.0    -3.0
    -5.5    -6.0    -6.0    -5.0    -5.0

    关于有效数字问题,保留几位有效数字以及同时要求保留几位小数的实现:需要用到setprecision,用以保留有效数字,加上fixed,用以保留特定几位小数

    例子

    // setprecision example
    #include <iostream>     // std::cout, std::fixed
    #include <iomanip>      // std::setprecision
    
    int main () {
      double f =3.14159;
      std::cout << std::setprecision(5) << f << '
    ';
      std::cout << std::setprecision(9) << f << '
    ';
      std::cout << std::fixed;
      std::cout << std::setprecision(5) << f << '
    ';
      std::cout << std::setprecision(9) << f << '
    ';
      return 0;
    }

    Output:

    3.1416
    3.14159
    3.14159
    3.141590000

    同时保留特定几位小数输出

    // modify floatfield
    #include <iostream>     // std::cout, std::fixed, std::scientific
    
    int main () {
      double a = 3.1415926534;
      double b = 2006.0;
    
      std::cout.precision(5);
    
      std::cout << "default:
    ";
      std::cout << a << '
    ' << b << '
    ' << c << '
    ';
    
      std::cout << '
    ';
    
      std::cout << "fixed:
    " << std::fixed;
      std::cout << a << '
    ' << b << '
    ' << c << '
    ';

    return 0; }

    Output:

    default:
    3.1416
    2006
    1e-010
    
    fixed:
    3.14159
    2006.00000
    0.00000
  • 相关阅读:
    解读Unity中的CG编写Shader系列十 (光滑的镜面反射(冯氏着色))
    解读Unity中的CG编写Shader系列八(多光源漫反射)
    Unity3d《Shader篇》漫反射
    解读Unity中的CG编写Shader系列八(镜面反射)
    渲染物体到一张UITexture上
    解读Unity中的CG编写Shader系列六(漫反射)
    解读Unity中的CG编写Shader系列五(理论知识)
    解读Unity中的CG编写Shader系列四(unity中的圆角矩形shader)
    解读Unity中的CG编写Shader系列三
    解读Unity中的CG编写Shader系列二
  • 原文地址:https://www.cnblogs.com/dmndxld/p/14348203.html
Copyright © 2011-2022 走看看