第一轮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
答案 0 :(得分:1)
调试你的程序!
使用调试器很容易,但您也可以使用 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 大于 {{1} },这是 8,所以我们停止迭代。
答案 1 :(得分:0)
稍微思考一下逻辑:
res
从零开始。i
被设置为 2i
以 5 的步长递增,因此 i
现在为 7res += i
=> res = 2 + 7
,所以 res
现在是 9。i
再次增加步长 5,所以 i
现在是 12