gpt4 book ai didi

c - 没有花括号的嵌套循环

转载 作者:太空宇宙 更新时间:2023-11-04 06:32:52 24 4
gpt4 key购买 nike

请帮帮我,我的头要炸了

#include<stdio.h>
int main(void){
unsigned short sum1=0;unsigned short counter=0;

printf("Enter the number of integers you want to sum\n");scanf("%hd",&counter);
for (unsigned int i=1;i<=counter;++i)
{
printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);

for(unsigned int j=1;j<=i;++j)
sum1 =sum1+j;// 1 iteration sum=1;
printf("The i is %d and the sum is %d\n\n",i,sum1);
}
return 0;
}

直到现在我读的书在嵌套循环中用来放置花括号但不是在这个例子...问题 1)为什么在第二次迭代中总和将是 3 而不是 2(我问这个是因为总和在转到嵌套 for 之前初始化为 0)?问题 2)为什么当我想 printf() 时 j 会出错?任何人都可以向我解释这个程序是如何工作的吗?我的意思是第一次迭代,第二次迭代....谢谢兄弟....

最佳答案

这段代码:

for (unsigned int i=1;i<=counter;++i)
{ printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);
for(unsigned int j=1;j<=i;++j)
sum1 =sum1+j;// 1 iteration sum=1;
printf("The i is %d and the sum is %d\n\n",i,sum1);}

相当于:

for (unsigned int i=1;i<=counter;++i) { 
printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);
for(unsigned int j=1;j<=i;++j) {
sum1 =sum1+j;// 1 iteration sum=1;
}
printf("The i is %d and the sum is %d\n\n",i,sum1);
}

这是因为在没有大括号的for-loop中,只有下一行被包含在循环中。

现在在第一次迭代中,您将获得:

"The i is 1 and the sum is 0"
"The i is 1 and the sum is 0"
"The i is 1 and the sum is 1" //Enters inner for-loop

第二个:

"The i is 2 and the sum is 1" //Hasn't reset yet
"The i is 2 and the sum is 0" //Reset
"The i is 2 and the sum is 3" //Sum was 0, then added 1 when j was 1,
//then added 2 when j was 2

现在,你不能打印 j 的原因是因为你的 printf 语句都在你内部的 for-loop 之外,所以 j 未定义:)

关于c - 没有花括号的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18748503/

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