简体   繁体   English

以下代码的结果是什么?

[英]What is the result of the following code?

Why the result is 7???为什么结果是7??? I can't find the log if that :(如果那样的话,我找不到日志:(

#include <stdio.h>
main() {
    int i, j, a = 1, b = 1;
    for (i = 1; i < 4; i++)
        for (j = 1; j < 3; j++)
            a = a + b;
    printf("a=%d", a);
}

The structure is like below结构如下

- Outer `for` loop
 - inner `for` loop
     - instruction

so the "instruction" (statement/block) will get executed inner for loop count times, for outer for loop count times.所以“指令”(语句/块)将在内部for循环计数次数内执行,对于外部for循环计数次数。

What is basically says is, add the value of b to the latest value of a (in a recurring way) to get the current value of a.什么是基本上说是,价值增加b到的最新值a (以循环方式)来获取的当前值。 Now , do that for "outer" number of time, for which, do the same for "inner" number of times.现在,对“外部”次数执行此操作,为此,对“内部”次数执行相同操作。

Outer for loop ==> 3 times,外部for循环 ==> 3 次,
inner for loop ==> 2 times内部for循环 ==> 2 次

So, final value = 3*2 (increment) + (initial) = (3*2)*1 + 1 = 7 .因此,最终值 = 3*2 (increment) + (initial) = (3*2)*1 + 1 = 7

The result is 7 because b is initialized as 1 and stays 1 the whole time.结果是 7,因为 b 被初始化为 1 并且一直保持为 1。 The outer loop is run 3 times (1, 2, 3), the inner loop is run 2 times (1 and 2), so there are 6 runs where b is added to a (which is initialized as 1).外循环运行 3 次(1, 2, 3),内循环运行 2 次(1 和 2),因此有 6 次运行,其中 b 被添加到 a(初始化为 1)。 1 + 6 = 7. 1 + 6 = 7。

In such scenarios, you should add a watch and debug your code line by line.在这种情况下,您应该添加监视并逐行调试代码。 I believe the shortcut is F11.我相信快捷方式是 F11。 Regards to why the output of your code is 7... The inner loop runs six times.关于为什么你的代码的输出是 7... 内循环运行了六次。 J loops twice - 1, 2, (ends when it is 3), and I loops thrice (1, 2, 3, 4 - end)... for a total of 2 X 3 = 6. J 循环两次 - 1, 2,(当它是 3 时结束),而 I 循环三次(1, 2, 3, 4 - 结束)......总共 2 X 3 = 6。

Since b is '1', you are basically adding the number 1 to a six times.由于 b 是“1”,因此您基本上是将数字 1 与 a 相加六次。 Since a started with '1', the output is:由于 a 以“1”开头,因此输出为:

a = 1 + 1 + 1 + 1 + 1 + 1 + 1 = 7一 = 1 + 1 + 1 + 1 + 1 + 1 + 1 = 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM