我发现很难理解 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
作为输入。
n7
和 n8
是迭代输入。或者他们为循环提供长度值。
第一个 for
循环循环 n8
的长度,而 i
小于或等于 n8
而第二个循环则以第一个循环的当前索引
(=i) 作为起点。它查看索引是否大于 n7
,然后通过从索引 (j) 中减去 one
来迭代返回 (j--),而 index
大于n7
。
计算是在第二个循环的迭代中进行的:它将 n6
乘以 two
。循环完成后,它返回 n6
的乘法。
在您的情况下,第一个循环将运行两次:
n8
= 1 并且 0 和 1 小于或等于。- 索引
0
成为循环 2 的起始索引
。j
= 0 并且大于 n7 (-2)。 - 由于 0 和 -1 大于 -2,因此该循环将运行两次。
- 在该循环期间,
n6
(1) 被乘以二。或1 * 2 * 2
- 第二个循环结束并返回到第一个循环,该循环再次运行,因为 1 等于 1。
- 现在索引
1
成为循环 2 的起始索引。 - 由于 1、0 和 -1 大于 -2,因此该循环将运行 3 次。
- 再次乘法:
4 * 2 * 2 * 2
- 循环 1 结束(两次迭代)。
n6
= 32。
此函数在给定迭代次数上返回 n
的 2 次方,其中 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>
关于c - 这些嵌套的 `for` 循环在 C 语言中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765701/