【问题标题】:C# % throws DivideByZeroException [closed]C# % 抛出 DivideByZeroException [关闭]
【发布时间】:2016-05-25 12:29:53
【问题描述】:
    public static List<int> getDenoms(long n)
    {
        List<int> result = new List<int>();
        for (int i = 1; i < n; i++)
        {
            if (n % i == 0)
            {
                result.Add(i);
            }
        }
        return result;
    }

    public static int getHighestPrime(List<int> seq)
    {
        int currentHigh = 1;
        foreach (int number in seq)
        {
            List<int> temp = getDenoms(number);
            if (temp.Count == 1)
            {
                if (number > currentHigh)
                {
                    currentHigh = number;
                }
            }
        }
        return currentHigh;
    }

我有当前的 C# 代码。所以,我有两种方法。在 getDenoms 方法中,我假设语句 n%i 不会抛出任何错误,因为 i 大于或等于 1,但它确实会抛出该错误。

我以如下方式使用了这两种方法:

        Console.WriteLine(getHighestPrime(getDenoms(600851475143)));

对代码抛出该错误的原因有任何见解吗?

【问题讨论】:

    标签: c# divide-by-zero


    【解决方案1】:

    原因是600851475143 对于int 来说太大

    您的循环变量iint,但您将其与long 进行比较。 600851475143 大于int.MaxValue,所以i 最终会溢出并在int.MinValue 处重新启动。然后它会增加直到它再次成为0,瞧:

    除零异常

    要解决此问题,请将循环变量的类型也更改为 long

    for (long i = 1; i < n; i++)
    

    【讨论】:

    • 如果我把所有的 int 值都改成 long 会起作用吗?
    • @Jihan 是的,将其添加到我的答案中。
    【解决方案2】:

    'i' 是一个 int,因为 'n' 很长,所以在 for cicle 中,'i' 溢出并在一段时间后达到 '0' 值。

    修复: for (long i = 1; i

    【讨论】:

      【解决方案3】:

      我自己没有对此进行测试,但是当我查看您的代码时,我发现您的循环使用了一个 int 变量,而您的输入是一个 long。您用来测试函数的数字,即 600851475143,大于 32 位 int 可以表示的数字。尝试将变量 i 更改为 long

      【讨论】:

        【解决方案4】:

        失败的原因是你的值600851475143大于int.MaxValue来解决这个问题继续使用long而不是int

        注意 long.MaxValue 是:9223372036854775807

        见下方代码

        public static List<long> getDenoms(long n)
        {
            List<long> result = new List<long>();
            for (long i = 1; i < n; i++)
            {
                if (n % i == 0)
                {
                    result.Add(i);
                }
            }
            return result;
        }
        
        public static long getHighestPrime(List<long> seq)
        {
            int currentHigh = 1;
            foreach (long number in seq)
            {
                List<long> temp = getDenoms(number);
                if (temp.Count == 1)
                {
                    if (number > currentHigh)
                    {
                        currentHigh = number;
                    }
                }
            }
            return currentHigh;
        }
        

        【讨论】:

          猜你喜欢
          • 2023-04-08
          • 2011-12-10
          • 1970-01-01
          • 2020-07-10
          • 2019-01-06
          • 2012-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多