计算平均分数

时间:2014-12-14 09:56:44

标签: c average

为什么我计算平均分数是错误的?

我有一个功能:

int student_average_scope() {
  char name[50];
  int group;
  int exam;
  int average = 0;
  int digit = 0;
  int counter_digits = 0;

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

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

    printf("%.1f\n", (double)average / counter_digits);
  }

  return 0;
}

student_list[i] = "4273 Константинопольский А. А. 4333 знзнз"平均值等于3.9,但正确回答3.2!如果我做简单的功能,计算平均分数给我正确的输出(3.2)。哪里弄错了?

int student_average_scope() {
    int exam = "4333";

    int average = 0;
    int digit = 0;
    int counter_digits = 0;

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

    printf ("%.1f\n", (double) average / counter_digits);

    return 0;
}

1 个答案:

答案 0 :(得分:5)

问题是,当您从for循环中的一个记录移动到下一个记录时,您无法将变量重置为零。你应该做的是:

  for (int i = 0; i < 4; i++) {
    average = 0;
    counter_digits = 0;
    ...