Compute the average of an int array as a double, and also rounded to the nearest whole number.
Solution
main.c
#include <math.h>
#include <stdio.h>
int main(void) {
int marks[] = {78, 91, 66, 85, 72, 90};
int n = sizeof marks / sizeof marks[0];
long sum = 0;
for (int i = 0; i < n; i++)
sum += marks[i];
double avg = (double) sum / n; /* convert before dividing */
printf("sum %ld, average %.2f, rounded %ld\n", sum, avg, lround(avg));
return 0;
}
Output Verified by compiling and running
sum 482, average 80.33, rounded 80
Casting sum to double before the division keeps the fraction. lround() rounds to the nearest integer (halves away from zero); a plain (long) avg would always truncate.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!