一、先说结论
x % y (此时 |x| ≤ |2y| )
1、都是正数时,整除完剩下的就是余数
5 % 3 = 2
2、存在一个负数时,有两种情况
①|x| > |y| 时,余数为 x+y
5 % -3 = 2
-5 % 3 = -2
②|x| ≤ |y| 时,余数为 x
3 % -5 = 3
-3 % 5 = -3
3、两个都是负数,有两种情况
①|x| > |y| 时,余数为 x-y
-5 % -3 = -2
②|x| ≤ |y| 时,余数为 x
-3 % -5 = -3
二、深层次解析余数
x / y
1、首先了解整除
①|x| ≥ |y| 时
5 / 3 = 1
5 / -3 = -1
-5 / -3 = 1
②|x| < |y| 时, 取整都为 0
3 / 5 = 0
3 / -5 = 0
-3 / -5 = 0
2、套公式 余数 = 被除数 - 商 * 除数
案例1:8 % -3 =8 - (8 / -3)* (-3)= 8 - (-2)*(-3)= 2
案例2:-8 % -3 = -8 - (-8 / -3)*(-3)= -8 - 2*(-3) = -2
三、代码验证
int main()
{
printf("%d\n",5 % 3); //2
printf("%d\n",5 % -3); //2
printf("%d\n",-5 % 3); //-2
printf("%d\n",-5 % -3); //-2
printf("%d\n",3 % 5); //3
printf("%d\n",3 % -5); //3
printf("%d\n",-3 % 5); //-3
printf("%d\n",-3 % -5); //-3
printf("%d\n",8 % 3 ); //2
printf("%d\n",8 % -3 ); //2
printf("%d\n",-8 % 3 ); //-2
printf("%d\n",-8 % -3 ); //-2
return 0;
}