gpt4 book ai didi

java - 如何计算溢出值的输出

转载 作者:行者123 更新时间:2023-12-02 01:31:01 25 4
gpt4 key购买 nike

我在面试中被问到一个与整数溢出有关的问题。问题很简单,但我找不到一个简单的解决方案来计算溢出值的结果。

例如,以下程序应打印 1000 作为输出,但由于整数溢出而打印 5。

public class IntegerOvewflow {

/**
* Java does not have target typing, a language feature wherein the type of the
* variable in which a result is to be stored influences the type of the
* computation.
*
* @param args
*/
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);

}
}

但是,这里我们可以使用任何特定的公式或方程来计算溢出值的输出。这里的数字确实很大,不容易用人的头脑快速判断输出。

最佳答案

指定它们是 longL,因为如果不是,您将进行 int 乘法,结果是 int 触及溢出,然后存储到 long

public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000L;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); // 1000
}

查看:https://ideone.com/5vHjnH

关于java - 如何计算溢出值的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56065789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com