如何使每个数字1-1000,显示它是什么,例如奇数/偶数,超过500

0 c# loops

好.我一直在尝试这段代码很久了.我想写一个打印出数字1-1000的程序.对于每个数字,我希望它显示它是奇数还是偶数,是否小于250,大于或等于250且小于500,大于或等于500且小于750或大于或等于750.这是我的代码,但它不起作用,我搜索了IE并找不到任何帮助.

for (int i = 0; i < 1001; i++) ;

        if ((i % 2) == 0)
        {
            Console.WriteLine(i + " is even ");
        }
        else
        {
            Console.WriteLine(i + " is odd ");
        }
        if (i < 250)
        {
            Console.WriteLine(" is less than 250");
        }
        else
        {
            Console.WriteLine("");
        }
        if (i >= 250)
        {
            if (i < 500)
            {
                Console.WriteLine(" is greater than or equal to 250 and less than 500 ");
            }
            else
            {
                Console.WriteLine("");
            }
            if (i >= 500)
            {
                if (i < 750)
                {
                    Console.WriteLine(" is greater than or equal to 500 and less than 750 ");
                }
                else
                {
                    Console.WriteLine("");
                }
                if (i >= 750)
                {
                    Console.WriteLine(" is greater than or equal to 750  ");
                }
                else
                {
                    Console.WriteLine("");
                }
                Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

我认为它是"我",因为有错误说它在当前的上下文中不存在.如何做到这一点它没有说,使代码更好?我有其余的正确吗?请帮忙.

Tud*_*dor 11

你的for循环永远不会执行任何操作,除了"空指令".删除;最后:

for (int i = 0; i < 1001; i++) ;
Run Code Online (Sandbox Code Playgroud)

还用花括号括起以下说明:

for (int i = 0; i < 1001; i++)
{
    // rest of instructions
}
Run Code Online (Sandbox Code Playgroud)


Dou*_*las 5

尝试删除它;后面,并将其余代码包含在{......中}.

您还可以通过将if... else语句合并在一起并删除冗余检查来显着减小代码的大小.

最后,不要忘记将您Console.ReadLine置于循环外(除非您想在每个数字后暂停程序).

for (int i = 0; i < 1001; i++)
{
    if ((i % 2) == 0)
        Console.Write(i + " is even ");
    else
        Console.Write(i + " is odd ");

    if (i < 250)
        Console.WriteLine("and is less than 250");
    else if (i < 500)
        Console.WriteLine("and is greater than or equal to 250 and less than 500 ");
    else if (i < 750)
        Console.WriteLine("and is greater than or equal to 500 and less than 750 ");
    else
        Console.WriteLine("and is greater than or equal to 750 ");     
}

Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)