试图找出平均分数......但是出错了

时间:2013-03-08 11:19:46

标签: c

朋友在下面的代码我试图得到一些浮动的平均值...我尝试手动我的ans应该在分数,但在这里它来自圆形无花果...请帮助我。

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

//finding out the average marks for students ....

float average (float []);

int main()
{
    int i;
    float total_avg=0;

    float arr_1[] = {10.2, 22.9, 36.04, 89.1, 94.1, 10.8,};

    for(i=0; i<6; i++)
             printf("%2f\n",arr_1[i]);
             printf("\n\n");


     total_avg = average (arr_1);   
     printf("Total average : %3f\n",total_avg);     


    system("PAUSE");
    return 0;

    }

float average (float a[5])
{
      int sum = 0, i;
      float total;

      for(i=0; i<6; i++)
      {
           sum = sum+a[i];
           }
     total = sum/5;

      return total;

   }

2 个答案:

答案 0 :(得分:1)

一旦你修正了bash.d所指出的sum类型,你的答案仍然是错误的。 arr_1包含6个元素,但在计算平均值时除以5。您需要将total的计算更改为

total = sum/6;

或者,更好的是,将average更改为

float average(float* a, int num_elems)
{
    float sum = 0
    int i;
    for(i=0; i<num_elems; i++) {
        sum += a[i];
    }
    return sum/num_elems;
}

并致电average,如

total_avg = average (arr_1, sizeof(arr_1)/sizeof(arr_1[0]));

答案 1 :(得分:1)

为什么使用int作为总和?请改用float

float average (float a[5])
{

  int sum = 0,
  float total, sum = 0.0f;

  for(i=0; i<6; i++)
  {
       sum = sum+a[i];
       }
 total = sum/5;

  return total;

}