循环将所有偶数相加

本文关键字:循环 | 更新日期: 2023-09-27 17:53:34

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

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

循环将所有偶数相加

试试这个:

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+。