當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。