Welcome to 9ilk's Code World
(๑•́ ₃ •̀๑) 个人主页: 9ilk
(๑•́ ₃ •̀๑) 文章专栏: C语言的小角落
本篇博客我们来深度理解取余/取模,以及它们在不同语言中出现不同现象的原因。
🏠 关于取整
🎵 向0取整
#include <stdio.h>
#include <windows.h>
int main()
{
//本质是向0取整
int i = -2.9;
int j = 2.9;
printf("%d\n", i); //结果是:-2
printf("%d\n", j); //结果是:2
int a = 5;
int b = -5;
printf("%d %d",a/2,b/2);
system("pause");
return 0;
}
测试结果:
我们发现测试结果中浮点数取整都是往0方向取整的:
其实在C库中有个trunc取整函数,也是向0取整:
🎵 向-∞取整
#include <stdio.h>
#include <math.h> //因为使用了floor函数,需要添加该头文件
#include <windows.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
system("pause");
return 0;
}
测试结果:
我们发现当调用floor函数取整时是结果都变小,往-∞方向取整: