所以,我有这段代码,对于前 4 个数字工作正常,但随后它给出了错误的数字,有什么问题吗? (我知道我也可以使用Math.pow,但我想先尝试自己做一下)
public static void main(String [] args){
int number = 98;
int result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
控制台: 9604 92236816 449273376
最佳答案
将您的int number
转换为long
,您将得到正确的结果。
public static void main(String [] args){
**long** number = 98;
**long** result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
它超出了 int 的范围并给出了奇怪的结果。 int
最多只能存储 2,147,483,647
- 98^4 远远超过了 (9,039,207,968)
关于java - 奇怪的指数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25017390/