取模运算与取余运算两个概念有重叠的部分但又不完全一致。主要的区别在于对负整数进行除法运算时操作不同。
对于整形数a,b来说,取模运算或者求余运算的方法都是:
1、求 整数商 c = a / b;
2、计算模或者余数 r = a - c* b .
取模运算和取余运算在第一步不同:
取余运算在取c值时,向0方向舍入;而取模运算在取c值时,是向负无穷方向舍入
各个环境下运算符%的含义不同,C/C++,Java为取余,python为取模
Java取余运算规则如下:
a%b = a - (a/b)*b
让我们先看一段代码:
public class Division_remainder {
public static void main(String[] args) {
int a = 13 / 5;
int b = 13 % 5;
int c = 5 / 13;
int d = 5 % 13;
int e = 13 / -5;
int f = -13 / 5;
int h = -13 % 5;
int j = 13 % -5;
System.out.println(a + "," + b);
System.out.println(c + "," + d);
System.out.println(e + &#