long型数字计算

在进行以亿为单位的数字计算时,int型往往会有溢出的问题,这时我们需要使用long型数字进行计算

public class demo04 {
    
    
    public static void main(String[] args) {
    
    
        //JDK7新特性,数字之间可以用下划线分割
        int money = 10_0000_0000;
        int years = 20;
        int total1 = money * years;     //-1474836480,计算结果溢出
        long total2 = money * years;    //默认是int,转换成long之前计算结果已经溢出
        long total3 = money*((long)years);//先把一个数转换为long

        System.out.println(total1);
        System.out.println(total2);
        System.out.println(total3);
    }
}

运算结果为:
在这里插入图片描述

total1为int型,面对运算结果为2,000,000,000的数字时会产生溢出;
total2虽然为long型,但只是将int型的100,000,000与20相乘的结果转为int型,而该计算结果已经溢出;
total3在运算时就将其中的一个数据转为了long型,这样运算结果为long型,并没有溢出。

猜你喜欢

转载自blog.csdn.net/qq_45361567/article/details/112602441