Bird
0
0

You want to compute the average of two integers in Ruby and ensure the result is a float. Which code snippet correctly achieves this?

hard📝 Application Q8 of 15
Ruby - Variables and Data Types
You want to compute the average of two integers in Ruby and ensure the result is a float. Which code snippet correctly achieves this?
a = 10
b = 15
average = ?
Aa / 2 + b / 2
B(a + b) / 2
C(a + b).to_f / 2
D(a.to_i + b.to_i) / 2.0
Step-by-Step Solution
Solution:
  1. Step 1: Understand integer division

    Dividing two integers returns an integer in Ruby.
  2. Step 2: Convert sum to float before division

    Converting the sum to float ensures float division.
  3. Step 3: Evaluate options

    (a + b).to_f / 2 converts sum to float before dividing by 2, giving a float average. (a + b) / 2 returns integer division. a / 2 + b / 2 sums integer divisions, losing precision. (a.to_i + b.to_i) / 2.0 converts integers redundantly and divides by float, but sum is integer so result is float; however, converting sum first is clearer.
  4. Final Answer:

    (a + b).to_f / 2 -> Option C
  5. Quick Check:

    Convert sum to float before division [OK]
Quick Trick: Convert sum to float before dividing [OK]
Common Mistakes:
  • Dividing integers directly causing integer division
  • Converting individual numbers instead of sum
  • Using integer division then converting result

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes