输出数量的理解问题

Comprehension problem with number of the output

第一轮2小于8,然后计算2加5。变量“i”现在应该有值 7。 最后 [res += i;] 被计算出来。所以我们计算0加7.

问题:在输出中我没有得到数字 9 但错误在哪里?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testing
{
    class testclass
    {
        static void Main()
        {
            int res = calc(2,8,5); // from = 2; to = 8; step = 5;
            Console.WriteLine(res);
            Console.ReadKey();
        }
        static int calc(int from, int to, int step = 1)
        {
            int res = 0;
            for (int i = from; i < to; i += step)
                res += i;
            return res;
        }
    }
}
Output: 9

调试你的程序!

使用调试器很容易,但您也可以使用 Console.WriteLine 进行简单的调试。这更容易在答案中显示,所以让我们这样做:

static int calc(int from, int to, int step = 1)
{
    int res = 0;
    for (int i = from; i < to; i += step)
    {
        Console.WriteLine($"Adding {i} to {res} to make {res + i}");
        res += i;
    }
    return res;
}

这给出了输出:

Adding 2 to 0 to make 2
Adding 7 to 2 to make 9
9

所以在第一个循环中,i = from 所以 i 是 2,我们将 2 添加到 0 得到 2。然后我们将 i 递增 step,即 5 , 得到 7.

在第二个循环中,i是7,所以我们将7加2得到9。然后我们再次递增i得到12。12大于to,也就是 8,所以我们停止迭代。

稍微思考一下逻辑:

  • res 开始时为零。
  • 第一次进入for循环,i设置为2
  • 下一次循环,i 增加步长 5,所以 i 现在是 7
  • res += i => res = 2 + 7,所以 res 现在是 9.
  • i 再次增加步长 5,所以 i 现在是 12
  • 第三次,循环条件不成立,for循环结束