今天闲来无事,看到篇HashMap工作原理的博客,在上面看到了mod(取模),就想到取余符号%。
然后就查看了一些资料,现在总结下:
Java中的取模和求余方式:
1、取模demo
package com.lbb.test;
import java.math.BigInteger;
public class RomTest {
public static void main(String[] args) {
BigInteger b1;
BigInteger b2;
BigInteger b3;
b1 = new BigInteger("-10");
b2 = new BigInteger("4");
b3 = b1.mod(b2);
System.out.println("b3:" + b3);
Integer i1 = -20;
Integer i2 = -3;
Integer i3 = i1 % i2;
System.out.println("i3:" + i3);
}
}
注意:通过取模mod()方法计算出来的值都是非负数,特别是取模里面的参数b2必须正数。
求余%符号,对被除数和除数没有特殊要求,只要求除数不能为零,否则会出现 java.lang.ArithmeticException(除零异常)
注意:通过%求余出来的数值,正数、负数、0都可以。