【问题标题】:C# user input for loop not working correctlyC# 用户输入 for 循环无法正常工作
【发布时间】:2014-03-01 15:38:29
【问题描述】:

我正在 C# 中创建一个程序来从用户输入的数字中打印数字,userInput1 = 1 和 UserInput2 = 10 然后打印数字 1 到 10,但如果 userInput1

Console.Write("Write a starting vlue: ");
int t1 = int.Parse(Console.ReadLine());
Console.Write("Write an ending value: ");
int t2 = int.Parse(Console.ReadLine());

int i = t1;
if (t1 < t2)
{
    for (i = t1; i <= t2; i--)
    {
        Console.WriteLine(i--);
    }
}

        for (i = t1; i <= t2; i++)
        {
            Console.WriteLine(i);
        }
        Console.ReadKey();
        }
    }
}

当我将第一个数字写为 20 并将第二个数字写为 1 时,我没有得到输出而不是 20、19、18、17、16...如果有人知道这个问题的解决方案,请分享。

【问题讨论】:

  • 第一个数字是 20:t1 = 20 而你的第二个数字是 1:t2 = 1;您正在检查 if (t1

标签: c# visual-studio-2010 visual-studio loops for-loop


【解决方案1】:

像这样更改for 循环并使用else 语句:

if (t1 < t2)
{
    for (i = t1; i <= t2; i++)
    {
        Console.WriteLine(i);
    }
}
else 
{
     for (i = t1; i >= t2; i--)
    {
        Console.WriteLine(i);
    }
}

在第一个循环中,您应该增加i,因为t1 小于t2。并且不要在循环主体内更改i 的值,因为您已经在每次迭代中更改它。如果您再次更改它,然后您将在每次迭代中跳过一个步骤。

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2020-01-30
    • 2012-02-19
    • 2015-08-12
    相关资源
    最近更新 更多