gpt4 book ai didi

c - 嵌套 for 循环的解释

转载 作者:太空宇宙 更新时间:2023-11-04 05:34:10 25 4
gpt4 key购买 nike

嗨,有人可以向我解释以下循环如何打印 45 吗?我想我不太了解这些嵌套循环是如何工作的:

#include <stdio.h>

int main() {
int x, y, n;
n = 0;
for (x = 0; x < 10; x++)
for (y = 0; y < x; y++)
n++;

printf("%d\n", n);
}

最佳答案

尝试展开第一个循环帮助自己理解。如果你这样做,你会得到这样的代码:

#include <stdio.h>  
int main() {
int x, y, n;
n = 0;

/* x=0 */
for (y=0; y<0; y++)
n++; /* doesn't get hit n=0 */

/* x=1 */
for (y=0; y<1; y++)
n++; /* gets hit once n=1 */

/* x=2 */
for (y=0; y<2; y++)
n++; /* gets hit twice n=3 */

/* x=3 */
for (y=0; y<3; y++)
n++; /* gets hit three times n=6 */

/* x=4 */
for (y=0; y<4; y++)
n++; /* gets hit four times n=10 */

/* x=5 */
for (y=0; y<5; y++)
n++; /* gets hit five times n=15 */

/* x=6 */
for (y=0; y<6; y++)
n++; /* gets hit six times n=21 */

/* x=7 */
for (y=0; y<7; y++)
n++; /* gets hit seven times n=28 */

/* x=8 */
for (y=0; y<8; y++)
n++; /* gets hit eight times n=36 */

/* x=9 */
for (y=0; y<9; y++)
n++; /* gets hit nine times n=45 */

/* x=10 exit loop */

printf ("%d\n", n); /* prints 45 */
}

关于c - 嵌套 for 循环的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com