将 95 阶乘打印为数字而不是指数函数

Print 95 factorial as a number and not as exponential function

当输入为 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);
        }
    }
}

.Net 4.0+ 中的 BigInteger class 支持任意大的整数,int 在表示多少位有效数字方面相对有限。

如上所述,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 . . .

您必须在解决方案中使用 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