gpt4 book ai didi

Java检查整数平方是否导致溢出

转载 作者:行者123 更新时间:2023-11-29 10:11:49 26 4
gpt4 key购买 nike

如何确定整数平方是否会导致溢出。所有大于 46340 的数的平方值都大于 java.lang 的最大整数值。由于 java 将对数字进行换行,因此 46431 的平方给出 -2147479015,而 2147483647 的平方给出 1,因此这进一步复杂化。同样不幸的是,我不能在 Java 8 中执行此操作,否则会抛出 ArithmeticException。那么有没有其他可能的方法来检查整数的平方是否会导致溢出?

最佳答案

public class SecureSquare {

private static final double SECURE_SQUARE_LIMIT = Math.sqrt(Integer.MAX_VALUE);

public static int square(int number) {
if (Math.abs(number) > SECURE_SQUARE_LIMIT) {
throw new ArithmeticException("Square overflow exception!");
}
return number * number;
}

public static void main(String[] args) {
int number = square(-46340);
System.out.println(number);
}
}

43640 的输出:

2147395600

43641 的输出:

Exception in thread "main" java.lang.ArithmeticException: Square overflow exception!
at com.artofcode.test.SecureSquare.square(SecureSquare.java:9)
at com.artofcode.test.SecureSquare.main(SecureSquare.java:15)
...

关于Java检查整数平方是否导致溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30948710/

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