Calculate the GPA
Why is my average estimate 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 the student_list[i] = "4273 . . 4333 "
average is 3.9, but the correct answer is 3.2! And if I do a simple function, calculate the GPA, give me the correct result (3.2). Where did I go wrong?
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;
}
+3
rel1x
source
to share
1 answer
The problem is that when you go from one record to the next in your loop, for
you don't reset the variables back to zero. What you have to do is:
for (int i = 0; i < 4; i++) {
average = 0;
counter_digits = 0;
...
+5
NPE
source
to share