C 庫 - round() 函式



C 庫的 round() 函式可以用來將浮點數舍入到最接近的整數。此函式是 C99 標準的一部分,並在 math.h 標頭檔案中定義。

假設我們有一個整數,例如 0.5 或以上,該函式將舍入到下一個整數,否則將其舍入到較小的整數。

語法

以下是 C 庫函式 round() 的語法 -

double round(double x);

引數

此函式僅接受一個引數 -

  • x - 此引數用於設定要舍入的浮點數。

返回值

此函式返回 x 的舍入值。假設 x 的小數部分為 0.5,則該函式將遠離零舍入。

示例 1

以下基本示例說明了 C 庫 round() 函式的用法。

#include <stdio.h>
#include <math.h>

int main() {
   double n1 = 8.6;
   double n2 = 6.2;
   double n3 = -31.6;
   double n4 = -32.2;
   double n5 = 32.5;
   double n6 = -12.5;

   printf("round(%.1f) = %.1f\n", n1, round(n1)); 
   printf("round(%.1f) = %.1f\n", n2, round(n2)); 
   printf("round(%.1f) = %.1f\n", n3, round(n3)); 
   printf("round(%.1f) = %.1f\n", n4, round(n4)); 
   printf("round(%.1f) = %.1f\n", n5, round(n5)); 
   printf("round(%.1f) = %.1f\n", n6, round(n6)); 

   return 0;
}

輸出

以上程式碼產生以下結果 -

round(8.6) = 9.0
round(6.2) = 6.0
round(-31.6) = -32.0
round(-32.2) = -32.0
round(32.5) = 33.0
round(-12.5) = -13.0

示例 2

該程式表示整數(正數和負數)的陣列,可用於使用 round() 函式計算最接近的整數。

#include <stdio.h>
#include <math.h>

int main() {
   double numbers[] = {1.2, 2.5, 3.7, -1.2, -2.5, -3.7};
   int num_elements = sizeof(numbers) / sizeof(numbers[0]);
   printf("The result of nearest integer is as follows:\n");
   for (int i = 0; i < num_elements; i++) {
       double rounded_value = round(numbers[i]);
       printf("round(%.1f) = %.1f\n", numbers[i], rounded_value);
   }

   return 0;
}

輸出

執行上述程式碼後,我們得到以下結果 -

The result of nearest integer is as follows:
round(1.2) = 1.0
round(2.5) = 3.0
round(3.7) = 4.0
round(-1.2) = -1.0
round(-2.5) = -3.0
round(-3.7) = -4.0
math_h.htm
廣告