英文:
My code is not producing the correct output
问题
long fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println(fact);
这段代码应该计算大数的阶乘,例如 25 的阶乘。但是输出结果不正确。
英文:
long fact= 1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println(fact);
The code should produce factorial of large numbers, for example 25. But the output is not correct.
答案1
得分: 3
Sure, here's the translation:
就像Samir Vyas所说的那样:
“它超出了Java long类型可以表示的数字范围。”
如果你想要绕过这个限制,你需要使用BigInteger
或者BigDecimal
。
你可以在这个问题中找到更多信息:https://stackoverflow.com/questions/849813/large-numbers-in-java
英文:
Like Samir Vyas said
"It exceeds the number range which can be represented by java long type."
If you want to bypass this limit, you will need to use a BigInteger
or a BigDecimal
.
You can find more information on this question https://stackoverflow.com/questions/849813/large-numbers-in-java
答案2
得分: 2
超出了 Java long
类型可以表示的数字范围。
链接:https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html
英文:
It exceeds the number range which can be represented by java long
type.
https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html
答案3
得分: 0
试一试这个。
int n = 30;
System.out.printf("%d! = %,d%n", n, fact(n));
public static BigInteger fact(int fact) {
BigInteger f = BigInteger.valueOf(fact);
while (--fact > 1) {
f = f.multiply(BigInteger.valueOf(fact));
}
return f;
}
输出结果
30! = 265,252,859,812,191,058,636,308,480,000,000
要了解更多关于任意精度数学的信息,请查看JDK API中的BigInteger和BigDecimal。
英文:
Try this.
int n = 30;
System.out.printf("%d! = %,d%n",n,fact(n));
public static BigInteger fact(int fact) {
BigInteger f = BigInteger.valueOf(fact);
while (--fact > 1) {
f = f.multiply(BigInteger.valueOf(fact));
}
return f;
}
Prints
30! = 265,252,859,812,191,058,636,308,480,000,000
For more information on arbitrary precision math check out BigInteger and BigDecimal in the JDK API.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论