- 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 库 - 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
广告