【问题标题】:Why the sum of the array elements always end up printing the same value?为什么数组元素的总和总是打印相同的值?
【发布时间】:2017-04-17 07:06:33
【问题描述】:
#include <stdio.h>
#include <stdlib.h>


int main()
{int array1[10],i=0,sum=0;

while(i<10)
{scanf("%d",&array1[i]);
i=i+1;
}
while(i<10)
{sum=sum+array1[i];i=i+1;
}

printf("sum =%d",sum);
   return 0;
}

代码编译正常,但运行时不会产生任何结果,总是打印 0。

【问题讨论】:

  • DO SEND CORRECTED CODE FOR ME TO CHECK IT ON MY COMPILE...emm...这是为什么呢?谁付钱?
  • 在将输入输入数组后,您不会将 i 重置为 0。
  • 学习使用调试器。它在调试小型(甚至中大型)程序时非常方便。如果您实际使用了调试器而不是在此处发布问题,那么找出错误所需的时间会更少。,
  • #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() {int array1[10],i=0,sum=0; while(i&lt;10) {scanf("%d",&amp;array1[i]); sum=sum+array1[i]; i=i+1; } printf("sum =%d",sum); return 0; } 大声笑你需要在学习时检查这些你自己。

标签: c arrays loops while-loop


【解决方案1】:

问题出在第二个循环中。在进入while 循环体及之后检查i 的值。

您需要重置i 的值。否则,第二个循环不会执行。执行第一个循环后,i 保持值 10,除非更改,否则第二个 while 循环条件评估为 false,因此循环体不执行,将 sum 保留为其初始化值。

也就是说,

  • 对于托管环境,int main() 最好是 int main(void)
  • 在使用扫描的值之前,始终检查scanf() 的返回值是否成功。

【讨论】:

  • 但我不能在第一次循环后写 int i =0
  • @AniketMalik 为什么会这样?
  • @AniketMalik 哎呀,不是int i =0;,是i =0;,就是这样。
【解决方案2】:

在第一次循环后初始化 i=0。在第一个循环结束时,i 的值为 10,因此它不会进入第二个循环。因此打印 0。

#include <stdio.h>
#include <stdlib.h>


int main()
{
    int array1[10],i=0,sum=0;

    while(i<10)
    {
        scanf("%d",&array1[i]);
        i=i+1;
    }

    i=0;          // Notice this line
    while(i<10)
    {
        sum=sum+array1[i];i=i+1;
    }

    printf("sum =%d",sum);
    return 0;
}

【讨论】:

    【解决方案3】:

    变量 i 在第二个循环中未初始化为 0。

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {int array1[10],i=0,sum=0;
    
    while(i<10)
    {scanf("%d",&array1[i]);
    i=i+1;
    }
    /*After the execution of 1st while loop i has 10 in it, that needs to be set to 0 for next loop execution, for this use case.
    
     If it is not mandatory to use while loop, try with **for loop**, it is far simple for this use case. */
    
    for( i=0; i<10; i++) //while( i<10)
    {sum=sum+array1[i];//i=i+1;
    }
    
    printf("sum =%d",sum);
       return 0;
    }
    

    否则使用单个循环,这会使您的代码更简单

    int main()
    {int array1[10],i,sum=0;
    
    for( i=0; i<10; i++){
       scanf("%d",&array1[i]);
       sum=sum+array1[i];
    }
    
    printf("sum =%d",sum);
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      相关资源
      最近更新 更多