1

请帮帮我,我的头已经准备好了

#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(我问这个是因为总和在去之前初始化为0嵌套的)?问题 2) 为什么当我想 printf() 时 j 会出现错误?谁能解释一下这个程序是如何工作的?我的意思是第一次迭代,第二次迭代......谢谢兄弟......

4

2 回答 2

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没有大括号的 s 中,只有下一行包含在循环中。

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

"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没有定义:)

于 2013-09-11T18:25:19.803 回答
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);

当有更多操作时,您需要一个花括号让编译器知道它们中有多少在 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);
}
效果很好,但j在 for 循环之外不可用。

于 2013-09-11T18:41:13.013 回答