深度理解取余运算
向零取整
首先打印一段代码
#include <stdio.h>
int main()
{
int i = -2.9;
int j = 2.9;
pritnf("%d\n, i");// -2
pritnf("%d\n, j");// 2
return 0;
}
打印出来发现,i的结果是-2,j的结果是2,有一个trunc函数和这个例子同作用
向负无穷取整
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.1f\n", floor(-2.9)); //-3
printf("%.1f\n", floor(-2.1)); //-3
printf("%.1f\n", floor(2.9)); //2
printf("%.1f\n", floor(2.1)); //2
return 0;
}
本质是向负无穷取整
向正无穷取整
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.1f\n", ceil(-2.9)); //-2
printf("%.1f\n", ceil(-2.1)); //-2
printf("%.1f\n", ceil(2.9)); //3
printf("%.1f\n", ceil(2.1)); //3
return 0;
}
本质是向正无穷取整
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.1f\n", round(2.1));
printf("%.1f\n", round(2.9));
printf("%.1f\n", round(-2.1));
printf("%.1f\n", round(-2.9));
return 0;
}
本质是四舍五入
汇总例子
#include <stdio.h>
#include <math.h>
int main()
{
const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
printf("value\tround\tfloor\tceil\ttrunc\n");
printf("-----\t-----\t-----\t----\t-----\n");
printf(format, 2.3, round(2.3), floor(2.3), ceil(2.3), trunc(2.3));
printf(format, 3.8, round(3.8), floor(3.8), ceil(3.8), trunc(3.8));
printf(format, 5.5, round(5.5), floor(5.5), ceil(5.5), trunc(5.5));
printf(format, -2.3, round(-2.3), floor(-2.3), ceil(-2.3), trunc(-2.3));
printf(format, -3.8, round(-3.8), floor(-3.8), ceil(-3.8), trunc(-3.8));
return 0;
}
结论:浮点数(整数/整数),是有很多取整方式的。