LearnFrenzy
Sign in Take a free test

Data Types · Data Type Programs · Question 5

Average of integers with correct rounding in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links