这些嵌套的 `for` 循环在 C 语言中是如何工作的?

How these nested `for` loops work in C language?

我很难理解 for 循环是如何工作的,尤其是当有多个循环时。如果是 f3(1,-2,1),那么这个函数返回什么?还有 n6=?语言是C。

int f3(int n6, int n7, int n8) {
    int i, j;

    for(i = 0; i <= n8; i++) {
        for(j = i; j > n7; j--) {
            n6 *= 2;
        }
    }

    return n6;
}

答案应为 32。

此函数需要 int 个数作为输入。

n7n8 是迭代输入。或者他们为循环提供长度值。

第一个for循环循环n8的长度,而i小于或等于n8

而第二个循环则以第一个循环的当前index(=i)为起点。它查看索引是否大于 n7,然后通过从索引 (j) 中减去 one 而迭代返回 (j--),而 index 大于 n7

计算是在第二个循环的迭代中进行的:它将 n6 乘以 two。循环完成后,returns 返回 n6 的乘法。

在你的情况下,第一个循环将 运行 两次:

  1. n8 = 1且0和1小于或等于。
  2. index 0 成为循环 2 的 starting indexj = 0 并且大于 n7 (-2)。
  3. 这个循环将 运行 两次,因为 0 和 -1 大于 -2。
  4. 在该循环中 n6 (1) 乘以两倍。或 1 * 2 * 2
  5. 第二个循环结束并返回到第一个循环,运行再次循环,因为 1 等于 1。
  6. 现在索引 1 成为循环 2 的起始索引。
  7. 这个循环将 运行 三次,因为 1、0 和 -1 都大于 -2。
  8. 再次乘法:4 * 2 * 2 * 2
  9. 循环 1 结束(两次迭代)。

n6 = 32.

这个函数 returns 的 2 次方 n 在给定的迭代次数上 n7 需要大于 n8,否则 n6将原样返回。


因为这几乎是 JavaScript 我们可以用示例代码来演示:

function f3(n6, n7, n8) {
    let i, j;

    for(i = 0; i <= n8; i++) {
        for(j = i; j > n7; j--) {
            n6 *= 2;
        }
    }

    return n6;
}

document.querySelector("button").addEventListener("click", function(){
  const n6 = document.querySelector("input.n6").value;
  const n7 = document.querySelector("input.n7").value;
  const n8 = document.querySelector("input.n8").value;
  
  console.log(f3(n6, n7, n8));
});
label{
 display: block;
 margin: 2px;
}

label > input{
  display: block;
  width: 50px;
}
<label>Input number <input class="n6"></label>
<label>value 1 <input class="n7"></label>
<label>value 2 <input class="n8"></label>

<button>Start</button>