问题描述
int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine(factorial);
这code在控制台应用程序运行,但是当一个数字是34以上的应用程序返回0。
This code runs in Console Application, but when a number is above 34 application returns 0.
为什么返回0,并可以做些什么来计算大数阶乘?
Why 0 is returned and what can be done to compute factorial of large numbers?
推荐答案
您打算出什么样的变量可以存储范围。这实际上是一个因子,生长比指数更快。尝试使用(最大值2 ^ 64 = 18,446,744,073,709,551,615),而不是INT(最大值2 ^ 31 = 2,147,483,647) - ULONG p = 1
- 这应该让你远一点。
You're going out of range of what the variable can store. That's effectively a factorial, which grows faster than the exponential. Try using ulong (max value 2^64 = 18,446,744,073,709,551,615) instead of int (max value 2^31 = 2,147,483,647) - ulong p = 1
- that should get you a bit further.
如果你需要更进一步,.NET 4及以上有<$c$c>BigInteger$c$c>,它可以存储任意大量涌现。
If you need to go even further, .NET 4 and up has BigInteger
, which can store arbitrarily large numbers.
这篇关于为什么计算realtively小数字阶乘(34+)返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!