循环添加所有偶数

时间:2014-03-26 03:49:56

标签: c# loops counter

如何添加1000-2000的所有偶数并显示总数? 如果你能帮助我,我会非常感激。

        int sum = 1000;
        int counter = 1;
        while (counter >= 2000)
        {
            if (counter % 2 == 0)
            {
                sum += counter; 
                counter++;
            }
        }
        Console.WriteLine("{0}", sum);
        Console.ReadLine();

1 个答案:

答案 0 :(得分:3)

试试这个:

var sum = Enumerable
    .Range(1000, 1001)
    .Where(n => n % 2 == 0)
    .Sum();

Console.WriteLine(sum);

要使代码正常工作,您应该看起来像这样:

int sum = 0;
int counter = 1000;
while (counter <= 2000)
{
    if (counter % 2 == 0)
    {
        sum += counter; 
    }
    counter++;
}

或者你可以这样做:

int sum = 0;
for (var counter = 1000; counter <= 2000; counter ++)
{
    if (counter % 2 == 0)
    {
        sum += counter; 
    }
}

或者这样:

int sum = 0;
for (var counter = 1000; counter <= 2000; counter ++)
{
    sum += (counter % 2 == 0) ? counter : 0; 
}

这是我的最爱:

int sum = 0;
var counter = 1000;
loop:
    sum += (counter % 2 == 0) ? counter : 0; 
    if (++counter > 2000)
        goto exit;
    goto loop;
exit:

希望你现在能得到一个A +。