Bird
0
0

You want to calculate the average of three large integer scores (e.g., 1000000000 each) in Kotlin and get a precise decimal result. Which code snippet correctly does this?

hard📝 Application Q15 of 15
Kotlin - Operators and Expressions
You want to calculate the average of three large integer scores (e.g., 1000000000 each) in Kotlin and get a precise decimal result. Which code snippet correctly does this?
Aval avg = (score1.toDouble() + score2.toDouble() + score3.toDouble()) / 3
Bval avg = (score1 + score2 + score3) / 3.0
Cval avg = (score1 + score2 + score3).toDouble() / 3
Dval avg = (score1 + score2 + score3) / 3
Step-by-Step Solution
Solution:
  1. Step 1: Understand integer division problem

    Dividing integers by integer 3 causes integer division, losing decimals.
  2. Step 2: Convert all scores to Double before division

    Converting each score to Double ensures floating-point division and precise average.
  3. Step 3: Check each option

    val avg = (score1.toDouble() + score2.toDouble() + score3.toDouble()) / 3 converts all scores to Double before adding and dividing, giving correct decimal average.
  4. Final Answer:

    val avg = (score1.toDouble() + score2.toDouble() + score3.toDouble()) / 3 -> Option A
  5. Quick Check:

    Convert all to Double before division for decimal average [OK]
Quick Trick: Convert all integers to Double before dividing for decimals [OK]
Common Mistakes:
MISTAKES
  • Dividing integers directly causing integer division
  • Converting sum to Double after integer division
  • Converting only one score to Double

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes