而循环不包括下限

  • 本文关键字:不包括 循环 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();

您的变量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);
    }
}

尝试这个

    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将在可分割操作

后首次增加

最新更新