gpt4 book ai didi

c - for循环的输出?

转载 作者:行者123 更新时间:2023-12-01 15:32:52 27 4
gpt4 key购买 nike

int main() {
int i,j,count;
count=0;
for(i=0; i<5; i++);
{
for(j=0;j<5;j++);
{
count++;
}
}
printf("%d",count);
return 0;
}

如果我们把 ;在 for() 之后,for 循环不运行任何东西。那么程序执行后count是如何变为1的呢?

最佳答案

出现了一次

 count++;

在只递增一次计数器的程序中。

解释:

int main() {
int i,j,count;
count=0;
for(i=0; i<5; i++);
{ // i == 5, count == 0
for(j=0;j<5;j++);
{ // i == 5, j == 5, count == 0
count++; // i == 5, j == 5, count == 1
}
}
printf("%d",count); //i == 5, j == 5, count == 1
return 0;
}

如你所说

here if we put ; after for() then for loop doesn't run anything.

不完全正确。如果将 ; 放在循环结构之后,它的行为就好像循环体是空的,即循环体中没有代码。循环仍在运行,下一个 block 不被视为循环体,而是无条件流的一部分。

不要仅仅被缩进所迷惑。你的代码,可以重写为

int main(void) {
int i,j,count;
count=0;
for(i=0; i<5; i++) // ; removed
{
// no code
}
{ // just another block, not previous loop body
for(j=0;j<5;j++) // ; removed
{
// again no code
}
{ // again just another block, not previous loop body
count++;
}
}
printf("%d",count);
return 0;
}

基本上可以归结为:

int main() {
int count = 0;

{
count++;
}

printf("%d",count);
return 0;
}

关于c - for循环的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59261181/

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