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
source to share