取整函数c
时间: 2025-03-14 20:11:10 浏览: 33
### C语言中的取整函数及其使用方法
#### `floor` 函数
`floor` 是一种向下取整的函数,无论数值是正还是负,都会朝负无穷方向取最接近的整数。其定义如下:
```c
double floor(double x);
float floorf(float x);
long double floorl(long double x);
```
调用此函数时需包含 `<math.h>` 头文件[^1]。
示例代码:
```c
#include <stdio.h>
#include <math.h>
int main() {
printf("floor(2.9): %.0lf\n", floor(2.9)); // 输出 2
printf("floor(-2.9): %.0lf\n", floor(-2.9)); // 输出 -3
return 0;
}
```
---
#### `ceil` 函数
`ceil` 是向上取整的函数,它会朝正无穷方向取最接近的整数。其定义如下:
```c
double ceil(double x);
float ceilf(float x);
long double ceill(long double x);
```
同样需要引入 `<math.h>` 头文件。
示例代码:
```c
#include <stdio.h>
#include <math.h>
int main() {
printf("ceil(2.1): %.0lf\n", ceil(2.1)); // 输出 3
printf("ceil(-2.1): %.0lf\n", ceil(-2.1)); // 输出 -2
return 0;
}
```
---
#### `round` 函数
`round` 是四舍五入取整的函数,遵循标准数学规则:当小数部分大于等于 0.5,则向远离零的方向取整;否则靠近零取整。其定义如下:
```c
double round(double x);
float roundf(float x);
long double roundl(long double x);
```
需要注意的是,在某些编译器环境下可能不支持该函数,因此建议确认环境兼容性后再使用[^4]。
示例代码:
```c
#include <stdio.h>
#include <math.h>
int main() {
printf("round(2.5): %.0lf\n", round(2.5)); // 输出 3
printf("round(-2.5): %.0lf\n", round(-2.5)); // 输出 -3
return 0;
}
```
---
#### `trunc` 函数
`trunc` 实现了向零取整的功能,即去掉数值的小数部分而保留整数部分。它的原型为:
```c
double trunc(double x);
float truncf(float x);
long double truncl(long double x);
```
此函数也依赖于 `<math.h>` 的导入[^3]。
示例代码:
```c
#include <stdio.h>
#include <math.h>
int main() {
printf("trunc(2.9): %.0lf\n", trunc(2.9)); // 输出 2
printf("trunc(-2.9): %.0lf\n", trunc(-2.9)); // 输出 -2
return 0;
}
```
---
### 总结对比表
| **函数名称** | **描述** | **例子** |
|--------------|------------------------------|------------------|
| `floor(x)` | 向下取整至最近的整数 | `floor(2.9)=2` |
| `ceil(x)` | 向上取整至最近的整数 | `ceil(2.1)=3` |
| `round(x)` | 四舍五入到最近的整数 | `round(2.5)=3` |
| `trunc(x)` | 去掉小数部分并返回整数部分 | `trunc(2.9)=2` |
以上四种函数均属于 `<math.h>` 库的一部分,适用于不同场景下的取整需求[^2].
阅读全文