1.向上取整
应用场景:
向上取整在需要确保计算结果不低于某个值、满足特定需求或保证计算精度的情况下被广泛应用。
2.代码实现:
方法1:
主要用到的公式:
#include <stdio.h>
#include <math.h>
int ceil_division(int x, int y) {
return (x + y - 1) / y;
}
int main() {
int x = 3;
int y = 2;
int z = ceil_division(x, y);
printf("结果为: %d\n", z);
return 0;
}
运行结果
z = 2
[Done] exited with code=0 in 1.175 seconds
方法2:
使用 ceil()函数
#include <stdio.h>
#include <math.h>
int main() {
double x = 3.9;
double result = ceil(x);
printf("向上取整后的结果为: %f\n", result);
return 0;
}
运行结果
result = 4.000000
[Done] exited with code=0 in 1.43 seconds
2.向下取整
直接用 /
#include <stdio.h>
int floor_division(int x, int y) {
return x / y;
}
int main() {
int x = 3;
int y = 2;
int z = floor_division(x, y);
printf("向下取整后的结果为: %d\n", z);
return 0;
}
运行结果:
z = 1
[Done] exited with code=0 in 1.015 seconds