即使使用长类型[重复],c#中的100个结果的因子函数为0

问题描述 投票:-1回答:1

这个问题在这里已有答案:

所以我有这个代码来确定100的阶乘。但是五十年代后它开始给出0.i搜索问题的结果并且每个人都说使用长变量。但即使我使用它,它仍然说答案是0.你告诉我我在哪里犯错误?

    static void Main(string[] args)
    {
        long c;
        int a = 100;
        c = a * (a - 1);
        for (int i=a-2; i>=1 ; i--)
        {
            c = c * i;
        }
        Console.WriteLine(c);
        Console.ReadLine();
    }`
c# factorial
1个回答
1
投票

long类型不足以存储100的阶乘。

使用BigInteger代替:

BigInteger c = new BigInteger(0);
int a = 100;
c = a * (a - 1);
for (int i = a - 2; i >= 1; i--)
{
    c = c * i;
}
Console.WriteLine(c);
Console.ReadLine();

为了使用BigInteger,您必须向系统添加对System.Numerics程序集的引用。 (link

© www.soinside.com 2019 - 2024. All rights reserved.