This program is meant to print the average of the marks, but it is wrong for some inputs. Use the visualizer (or gdb) to find the bug, then fix it.
Input
The first line has n (1 ≤ n ≤ 100). The second line has the n marks (each from 0 to 100).
Output
The average with exactly two digits after the point.
Examples
Example 1 · Input
4 70 85 90 64
Expected output
77.25
Example 2 · Input
2 50 50
Expected output
50.00
Hints
Hint 1
Step through the program and watch total, n and total / n.
Hint 2
Dividing two ints throws away the fraction before the result becomes a double.
Hint 3
Make one side a double: (double)total / n.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
double average(int a[], int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += a[i];
}
return (double)total / n;
}
int main(void) {
int n, marks[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &marks[i]);
printf("%.2f\n", average(marks, n));
return 0;
}