How do I add all even numbers from 1000-2000 and display the total? If you could help me I would be very thankful.

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

解决方案

Try this:

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

Console.WriteLine(sum);

To get your code to work you should have it look like this:

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

Or you could do it this way:

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

Or this way:

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

This one is my favourite:

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

Hopefully you can now get an A+.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top