C 库 - round() 函数

❮ C 标准库 - <math.h>


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
", n1, round(n1)); 
   printf("round(%.1f) = %.1f
", n2, round(n2)); 
   printf("round(%.1f) = %.1f
", n3, round(n3)); 
   printf("round(%.1f) = %.1f
", n4, round(n4)); 
   printf("round(%.1f) = %.1f
", n5, round(n5)); 
   printf("round(%.1f) = %.1f
", 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("最接近整数的结果如下:
");
   for (int i = 0; i < num_elements; i++) {
       double rounded_value = round(numbers[i]);
       printf("round(%.1f) = %.1f
", numbers[i], rounded_value);
   }

   return 0;
}

输出

执行上述代码后,我们得到以下结果 -

最接近整数的结果如下:
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

❮ C 标准库 - <math.h>