LearnFrenzy
Sign in Take a free test

Data Types · Find the Error · Question 5

Bug: average computed with integer division Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The average of 7 marks totalling 52 should be 7.43. What does the program print, and why?

main.c
#include <stdio.h>

int main(void) {
    int total = 52, count = 7;
    double avg = total / count;
    printf("%.2f\n", avg);
    return 0;
}
  • A 7.43
  • B 7.42
  • C 7.00 – total / count is integer division; the fraction is lost before the result is stored in avg Correct
  • D It does not compile
Correct Answer: Option C

Both operands are int, so the division truncates to 7, and only then is 7 converted to 7.0. Write (double) total / count so the division itself happens in floating point.

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