计算平均分组

标签 c

我有一个数组,其中每个元素都是关于学生的符号:

group number | name | evaluations
---------------------------------
4272 Галкин Г. А. 5445
4273 Константинопольский А. А. 4333
4273 Курочкин А. А. 3433
4272 Козлов И. И. 4443

我需要计算每组的平均分,即在这种情况下获得两个数字:

  • (5 + 4 + 4 + 5) + (4 + 4 + 4 + 3) = 33/2 = 16.5
  • (4 + 3 + 3 + 3) + (3 + 4 + 3 + 3) = 26/2 = 13

因此,在输出中我应该得到:4272 -- 16.54273 -- 13。请告诉我,我该怎么做。

我的函数目前看起来像:

void group_average_scope() {
  char name[50];
  int group;
  int exam;

  for (int i = 0; i < 4; i++) {
    int sum_of_evaluations = 0;
    int digit = 0;
    int counter_digits = 0;

    sscanf(student_list[i], "%d %[^0-9] %d", &group, name, &exam);

    while (exam > 0) {
      digit = exam % 10;
      sum_of_evaluations += digit;
      counter_digits++;
      exam = exam / 10;
    }
  }
}

最佳答案

这样试试。 (此代码为伪代码。)

#define GROUP_NUM 5000
typedef struct list{
    int group;
    int number_of_students;
    int sum_of_eval;
    list(){group = 0; number_of_students = 0; sum_of_eval = 0;};
};

到这里为止,我做了一个结构来保存一个组的信息,该组的学生人数和评价总和。

char name[50];
  int group;
  int exam;
  list students_group[GROUP_NUM];

  for (int i = 0; i < 4; i++) {
    int sum_of_evaluations = 0;
    int digit = 0;
    int counter_digits = 0;
    sscanf(student_list[i], "%d %[^0-9] %d", &group, name, &exam);

    printf("%d %s %d\n",group,name,exam);//test

    while (exam > 0) {
      digit = exam % 10;
      sum_of_evaluations += digit;
      counter_digits++;
      exam = exam / 10;
    }
    students_group[group].group = group;
    students_group[group].number_of_students++;
    students_group[group].sum_of_eval += sum_of_evaluations;
  }
  for( group = 0 ; group < GROUP_NUM; group++){
    if(students_group[group].group > 0){
        printf("%d -- %g\n",students_group[group].group ,
               (double)students_group[group].sum_of_eval / students_group[group].number_of_students);
    }
  }

我不知道“组”的信息。所以我假设“组”存在于 0 到 4999 之间。 并在此函数中打印平均值。 如果要保存平均值,则必须接收结构指针。 如果您有任何疑问,请发邮件给我。

关于计算平均分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27652672/

相关文章:

c - ldd 命令从哪里检索依赖信息?

c - Cygwin 中的信号处理行为

c - 在 scanf 函数中使用指向矩阵的指针

c - 优化 "i = b ? (i | mask) : (i & ~mask)"

从另一个进程关闭 XLib 应用程序

c - 查找 pcap.h 和链接时出现问题

c - recvfrom无限接收问题

c - OpenGL:按下显示窗口时形状改变位置

c - 从命令行传入文件名来读取文件内容

c++ - 在条件表达式中使用时,gcc 或其他编译器是否自动将按位或转换为 bool 值或?