
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
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
廣告