当输入为25
时,预期输出为15511210043330985984000000
而非1.551121e+25
。解析虽然由Decimal.Parse(factorial.ToString(), System.Globalization.NumberStyles.Float)
解决。
我无法计算更大的数字,比如95。
using System;
namespace bigNumber
{
class Program
{
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
long factorial = 1;
for (int i = number; i > 0; i--)
{
factorial = factorial * i;
}
Console.WriteLine(factorial);
}
}
}
答案 0 :(得分:4)
您必须在解决方案中使用BigInteger
:
using System.Numerics;
using System.Linq;
...
int n = 95;
BigInteger factorial = Enumerable
.Range(1, n)
.Select(x => (BigInteger) x)
.Aggregate((f, v) => f * v);
Console.WriteLine(factorial);
答案是
10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000
请注意,factorial
远远超出 long.MaxValue
答案 1 :(得分:3)
如上所述,BigInteger是一个很好的候选者,因为它可以保存一个任意大的有符号整数:
namespace ConsoleApplication4
{
using System;
using System.Numerics;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Factorial(0));
Console.WriteLine(Factorial(25));
Console.WriteLine(Factorial(95));
}
private static BigInteger Factorial(int number)
{
BigInteger factorial = 1;
for (var i = number; i > 0; i--)
{
factorial *= i;
}
return factorial;
}
}
}
1
15511210043330985984000000
10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000
Press any key to continue . . .
答案 2 :(得分:1)
.Net 4.0+中的BigInteger类支持任意大整数,int相对限制它代表的有效位数。