Bird
0
0

You want to calculate the average of two integers a and b in C and get a floating-point result. Which code snippet correctly does this?

hard📝 Application Q15 of 15
C - Operators and Expressions
You want to calculate the average of two integers a and b in C and get a floating-point result. Which code snippet correctly does this?
Afloat avg = (a + b) / 2.0;
Bfloat avg = (a + b) / 2;
Cint avg = (a + b) / 2.0;
Dfloat avg = a / b + 2;
Step-by-Step Solution
Solution:
  1. Step 1: Understand integer vs floating-point division

    Dividing by 2 (integer) causes integer division, losing decimals. Dividing by 2.0 (double) forces floating-point division.
  2. Step 2: Check each option for correct average calculation

    float avg = (a + b) / 2; does integer division then converts to float, losing decimals. float avg = (a + b) / 2.0; divides by 2.0, giving float result. int avg = (a + b) / 2.0; stores float result in int, losing decimals. float avg = a / b + 2; is incorrect formula.
  3. Final Answer:

    float avg = (a + b) / 2.0; -> Option A
  4. Quick Check:

    Divide by 2.0 for float average [OK]
Quick Trick: Divide by 2.0 to get float average [OK]
Common Mistakes:
  • Dividing by integer 2 causing integer division
  • Storing float result in int variable
  • Wrong formula for average

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Quizzes