Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the average score

Tags:

c

average

Why my calculate the average score is wrong?

I have a function:

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;
}

Where student_list[i] = "4273 Константинопольский А. А. 4333 знзнз" average is equal 3.9, but right answer 3.2! And if I make simple function, calculate the average score give me right output (3.2). Where I made mistake?

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;
}
like image 894
rel1x Avatar asked Dec 06 '25 08:12

rel1x


1 Answers

The issue is that you are failing to reset the variables back to zero when you move from one record to the next in your for loop. What you should do is this:

  for (int i = 0; i < 4; i++) {
    average = 0;
    counter_digits = 0;
    ...
like image 176
NPE Avatar answered Dec 07 '25 21:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!