Bird
0
0

You want to calculate the average of two numbers in Ruby, where both are Integers. Which code correctly calculates the average as a Float?

hard📝 Application Q15 of 15
Ruby - Variables and Data Types
You want to calculate the average of two numbers in Ruby, where both are Integers. Which code correctly calculates the average as a Float?
a = 8
b = 5
average = ?
A(a + b) / 2.0
B(a + b) / 2
C(a.to_i + b.to_i) / 2
Da / 2 + b / 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand division with integers and floats

    Dividing an Integer truncates if both operands are integers; dividing by a Float keeps decimal.
  2. Step 2: Check each option for correct average calculation

    (a + b) / 2: 13 (Integer) / 2 (Integer) = 6 (truncated).
    (a + b) / 2.0: 13 / 2.0 = 6.5 (Float).
    (a.to_i + b.to_i) / 2: forces Integers, result 6 (Integer).
    a / 2 + b / 2: 8/2 + 5/2 = 4 + 2 = 6 (Integer divisions).
  3. Final Answer:

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

    Divide sum by float 2.0 for float average [OK]
Quick Trick: Divide by 2.0 to keep float result for average. [OK]
Common Mistakes:
  • Dividing by integer causing integer division
  • Converting floats to integers losing decimals
  • Not using float divisor for average

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes