[英]Why is the value of f when I print it always 0?
I wrote this little program in java, and the value of f is always 0. I dont see the logical error.I did this exact same thing in python and it works flawlessly.我在 java 中编写了这个小程序,f 的值始终为 0。我没有看到逻辑错误。我在 python 中做了完全相同的事情并且它完美地工作。 I dont get what im missing.我不明白我缺少什么。
public class factorial{
public static void main(String[] args){
int n = 1;
int f = 1;
while (true){
n++;
f = f * n;
System.out.println(f);
}
}
}
In fact, you do not always get 0. Your output looks like this:事实上,你并不总是得到 0。你的 output 看起来像这样:
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
1932053504
1278945280
2004310016
2004189184
-288522240
-898433024
109641728
-2102132736
-1195114496
-522715136
862453760
-775946240
2076180480
-1853882368
1484783616
-1375731712
-1241513984
1409286144
738197504
-2147483648
-2147483648
0
0
0
0
...
This is problem with int overflow in infinite loop.这是无限循环中 int 溢出的问题。
I don't familiar with Python, but if you want something int
without overflow, you can look at BigInteger
class in Java. Python我不熟悉,但是如果你想要int
而不溢出,你可以看看Java中的BigInteger
class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.