请帮助我,我的脑袋准备吹了
#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(我问这是因为sum在转到嵌套之前初始化为0)? 问题2)为什么当我想printf()j命中错误? 任何人都可以解释我这个程序的工作原理吗? 我的意思是第一次迭代,第二次迭代......谢谢兄弟......
答案 0 :(得分:3)
此代码:
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
未定义:)
答案 1 :(得分:1)
在C语言中,您无法在for循环序列中声明变量:
for(int i=0; i<=10; i++)
错了
int i;
for (i=0; i<=10; i++)
是正确的
您也可以说int a,b,c=3;
而不是单独声明int a, int b, int c=3;
为了帮助解决你的问题(我希望我可以评论,但我需要更多的声誉),如果你的声明(for,if,while)只有一个(或没有)操作,你不需要卷曲大括号:
for (i=0; i<=10; i++)
printf("%i ", i);
当进行更多操作时,你需要一个花括号来为compilator知道它们中有多少是在for循环中:
for (i=0; i<=10; i++){
printf("%i ", i);
if(i%2==1)
printf("Odd number");
printf("\n");
}
修改:
int i;
for(i=0; i<=10; i++){
int j = i+5;
printf("%i", j);
}
工作得非常好,但在for循环之外不能使用j
。