请帮帮我,我的头要炸了
#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/