当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C语言 round用法及代码示例


C语言math头文件(math.h)中round函数的用法及代码示例。

用法:

     double round  (double x);
      float roundf (float x);
long double roundl (long double x);
四舍五入到最接近的
返回最接近的整数值x,中途情况从零舍入。

标头<tgmath.h>提供此函数的type-generic宏版本。
额外的过载在此头文件中提供(<cmath>) 为了整数类型:这些重载有效地转换x到一个double计算之前(为T有任何整数类型)。

参数

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;
}


输出:

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

相关用法


注:本文由纯净天空筛选整理自C标准库大神的英文原创作品 C round function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。