C语言怎么取余取整
时间: 2025-05-25 10:18:31 浏览: 34
### C语言中取余和取整的操作方法
#### 取余操作
在C语言中,取余操作通过 `%` 运算符实现。它适用于整数类型的变量,能够返回两数相除后的余数。需要注意的是,如果参与运算的数值之一为负数,则结果的符号取决于被除数的符号[^4]。
```c
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Remainder of %d divided by %d is %d\n", a, b, a % b); // 输出:Remainder of 10 divided by 3 is 1
int c = -10, d = 3;
printf("Remainder of %d divided by %d is %d\n", c, d, c % d); // 输出:Remainder of -10 divided by 3 is -1
return 0;
}
```
---
#### 取整操作
C语言提供了多种方式进行取整操作,主要依赖于标准库 `<math.h>` 中定义的一系列函数。以下是常用的几个函数及其作用说明:
- `floor(double x)`:返回不大于x的最大整数值。
- `ceil(double x)` :返回不小于x的最小整数值。
- `round(double x)`:按照四舍五入原则返回最接近x的整数值。
- `(int)x` 或者强制转换成整型:直接截断小数部分只保留整数位[^5]。
```c
#include <stdio.h>
#include <math.h>
int main(){
double num1=4.8 ,num2=-3.2;
printf("Floor value of %.1lf : %.f \n",num1,floor(num1)); // Floor value of 4.8 : 4
printf("Ceiling value of %.1lf : %.f \n",num1,ceil(num1));// Ceiling value of 4.8 : 5
printf("Rounding off %.1lf : %.f \n",num2,round(num2)); // Rounding off -3.2 : -3
printf("Truncating after decimal point from %.1lf : %.f \n",(double)(int)num2,(int)num2 );// Truncating after decimal point from -3.2 : -3
return 0 ;
}
```
上述代码片段演示了如何使用这些函数来进行不同模式下的取整操作,并打印相应的结果以便观察效果。
---
#### 特殊注意事项
当涉及到浮点数时,由于计算机内部表示的原因可能会引发一些微小误差累积问题,因此建议在实际项目里谨慎对待浮点数相关的精确度敏感场景。另外值得注意的是,对于非整数类型的数据做模运算(`%`)会编译报错,此时可借助其他数学技巧或者第三方库解决类似需求[^6]。
---
阅读全文
相关推荐


















