而循环不包括下限

时间:2015-12-05 11:07:51

标签: c#

我正在通过本书学习C#,并希望得到一些帮助。 我想创建一个简单的控制台程序,允许用户输入两个数字作为下限和上限。然后程序将找到所有可被数字整除的数字(比方说3)。我到目前为止编写的代码有效但有一个小问题,它在找到可分数时不包括下限。可能是导致问题的while循环中的num1++;。请看一下:

int num1, num2, result;

Console.WriteLine("Enter the first number to be the lower limit: ");
num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the second number to be the upper limit: \n");
num2 = Convert.ToInt32(Console.ReadLine());

while (num1 <= num2)
{
    num1++;
    result = num1 % 3;

    if (result == 0)
    {
        Console.WriteLine("{0} is divisible by 3.\n", num1);
    }

}
Console.ReadLine();

2 个答案:

答案 0 :(得分:1)

您的变量num1在进入循环体后立即增加。将num1++;块之后的if行放在循环体的最末端。为了避免这样的错误,for(...)循环在迭代后续数字时更有用。

以下是使用for循环重写代码的示例:

int num1, num2, result;

Console.WriteLine("Enter the first number to be the lower limit: ");
num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the second number to be the upper limit: \n");
num2 = Convert.ToInt32(Console.ReadLine());

for (int current = num1; current <= num2; current++)
{
    result = current % 3;

    if (result == 0)
    {
        Console.WriteLine("{0} is divisible by 3.\n", current);
    }
}

答案 1 :(得分:0)

试试这个

    int num1, num2, result;

    Console.WriteLine("Enter the first number to be the lower limit: ");
    num1 = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter the second number to be the upper limit: \n");
    num2 = Convert.ToInt32(Console.ReadLine());

    while (num1 <= num2)
    {
        result = num1++ % 3;

        if (result == 0)
        {
            Console.WriteLine("{0} is divisible by 3.\n", num1 - 1);
        }

    }
    Console.ReadLine();

num1将在可分割操作后第一次增加