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;
}
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;
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With