2021_2_18_运算中数字溢出问题

运算中数字溢出问题

在运算中,可能会出现结果越界的情况,比如:

public class OverflowProblem {
    public static void main(String[] args) {
        int a = 10_0000_0000;
        int b = 20;
        int result = a*b;
        System.out.println(result);
    }
}


//   -1474836480

a乘以b的结果超过了int的边界,因此出现了溢出的情况。那么把result的类型改为long可以吗?

public class OverflowProblem {
    public static void main(String[] args) {
        int a = 10_0000_0000;
        int b = 20;
        long result = a *b;
        System.out.println(result);
    }
}


//   -1474836480

结果依然不行,那么如何才能解决这个问题呢?

public class OverflowProblem {
    public static void main(String[] args) {
        int a = 10_0000_0000;
        int b = 20;
        long result = (long) a * b;
        System.out.println(result);
    }
}


//   20000000000

只要在运算中对其中一个对象强制转换为long类型即可。

posted @ 2021-02-18 19:43  cutomorrow  阅读(135)  评论(0)    收藏  举报