并非所有路径都返回匿名方法中的值

时间:2013-07-31 17:11:06

标签: c# linq

我正在尝试创建一个检查数字是否丰富的方法(所有正确除数的总和大于数字本身的总和),但我在1.ToInc(28123, 1)代码行中出现错误:“并非所有代码路径都返回类型为System.Func<int,bool>的匿名方法中的值”。我相信这是指我的isAbundant方法。 isAbundant中的内容未返回值?

public void Solve ()
{
    //Check if number is abundant -> number < sum of proper divisors. memoize this
    Func<int, bool> isAbundant = x =>
    {
        return x < ProperDivisors (x).Select(x => x).Sum () && x >= 0;
    };

        isAbundant = isAbundant.Memoize ();

        //make a sequence of all these numbers for readability
        var seq = 12.ToInc (28123, 1).TakeWhile (x => isAbundant (x));

                    // take all the numbers between 13 and 28123 take while (from 12 to number / 2 from sequence) check if number - item from sequence isn't abundant
        1.ToInc (28123, 1).TakeWhile (x => {
            foreach (var i in seq){
                if (i < x/2){
                    if (isAbundant (x - i))
                        return false;
                    else
                        return true;
                }
            }
        })
        // Sum
        .Sum ().Display ();
    }
}

1 个答案:

答案 0 :(得分:2)

这实际上是指你的lambda:

.TakeWhile (x => {
        foreach (var i in seq){
            if (i < x/2){
                if (isAbundant (x - i))
                    return false;
                else
                    return true;
            }
        }

        // If there are no elements in seq, you'll reach here, and never return a value!
        // Add something here, ie:
        return false;
    })