C++ Reference: Standard C++ Library reference: C Library: cmath: round

发布于:2022-12-04 ⋅ 阅读:(493) ⋅ 点赞:(0)

C++官网参考链接:https://cplusplus.com/reference/cmath/round/

函数 
<cmath> <ctgmath>
round
C99
double round(double x);      
float roundf(float x);
long double roundl(long double x);
C++11
double round(double x);      
float round(float x);
long double round(long double x);     
double round (T x);   // additional overloads for integral types

向最近舍入 
返回最接近x的整数值,中间情况舍入到远离0。
C99
头文件<tgmath.h>提供了该函数的类型泛型宏版本。 
C++11
在此头文件(<cmath>)中为整型(integral types)提供了额外的重载:这些重载在计算之前有效地将x转换为double类型(定义为T为任何整型(integral types))。

形参
x
将要舍入的x。

返回值
x的值向最接近的整数值舍入(作为浮点值)。

用例
/* round vs floor vs ceil vs trunc */
#include <stdio.h>      /* printf */
#include <math.h>       /* round, floor, ceil, trunc */

int main ()
{
  const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
  printf ("value\tround\tfloor\tceil\ttrunc\n");
  printf ("-----\t-----\t-----\t----\t-----\n");
  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;
}
输出:

另请参考
floor         Round down value (function) (向下舍入取值(函数))
ceil           Round up value (function) (向上舍入取值(函数))
trunc        Truncate value (function) (截断取值(函数))
nearbyint Round to nearby integral value (function) (舍入到附近整数(函数))
rint           Round to integral value (function) (舍入到整数(函数))

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到