长整除

public class Main3 {
	public static void main(String[] args) {
		final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;//一天有多少微秒
		final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;//一天有多少毫秒
		
		System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);//出乎意料的输出!
		
		//计算以int执行,完成之后才提升为long,但是太迟了,已经溢出。
		//因为相乘的因子都是int,所以会得到int。Java不具有目标确定类型的特性
		System.out.println(MICROS_PER_DAY);//overflow...
		
		//将其中一个因子改为long型即可,注意不要用小写的L,因为1000l容易误认为是10001,你看出区别了么?~~
		long t = 24 * 60 * 60 * 1000 * 1000L;
		System.out.println(t);//ok...
		
		//如果遇到long的因子之前已经溢出了,也会得到错误的结果
		t = 24 * 60 * 60 * 1000 * 1000 * 1000 * 1000L;
		System.out.println(t);//overflow...
		//所以最好的方式是将第一个数采用long,保证之后的计算都采用long完成
		t = 24L * 60 * 60 * 1000 * 1000 * 1000 * 1000;
		System.out.println(t);//ok...
	}
}

你可能感兴趣的:(Java解惑)