【问题标题】:Why is my code outputting 0 when I run it? whats wrong and how do I fix it?为什么我的代码在运行时输出 0?出了什么问题,我该如何解决?
【发布时间】:2014-10-08 00:01:47
【问题描述】:

这是我的代码,用于使用 for 循环显示数组的总和和平均值,但是当我运行它时,它只为总和和平均值输出 0。

#include <stdio.h>

int main (void){

    float grades[12] = {85.0, 77.0, 15.0, 100.0, 90.0, 98.0, 62.0, 84.0, 86.0, 70.0, 100.0, 99.0};
    int counter;
    float average;
    float sum = 0.0;

    for(counter = 0; counter == 12; counter++){

        sum = sum + grades[counter];
    } 

    average = sum/12;

    printf("The sum of the grades is: %f \n", sum);
    printf("The average of the grades are: %f \n", average);

    system("pause");

}

【问题讨论】:

    标签: c arrays for-loop output average


    【解决方案1】:

    for 循环是:for(init; while; increment)

    请注意,这是 WHILE,而不是 UNTIL

    你的循环永远不会运行:

    for(counter = 0; counter == 12; counter++){
    

    因为 0 永远不等于 12。

    【讨论】:

      【解决方案2】:

      您的for-loop 是错误的。试试

      for(counter = 0; counter < 12; counter++) {
          ...
      }
      

      【讨论】:

        【解决方案3】:

        for 在其条件为假时立即停止。您的条件counter == 12 在第一次迭代时为假,因此循环永远不会运行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-14
          • 2021-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-27
          • 2020-08-26
          相关资源
          最近更新 更多