Bird
0
0

Given this Swift code, what is the correct way to store the result of dividing two Ints as a Float with decimal precision?

hard📝 Application Q9 of 15
Swift - Data Types

Given this Swift code, what is the correct way to store the result of dividing two Ints as a Float with decimal precision?

let a: Int = 7
let b: Int = 2
let result = ???
Alet result = Double(a / b)
Blet result = Float(a / b)
Clet result = Float(a) / Float(b)
Dlet result = a / b as Float
Step-by-Step Solution
Solution:
  1. Step 1: Understand integer division behavior

    a / b with Ints does integer division, losing decimals.
  2. Step 2: Convert operands before division

    Convert a and b to Float before division to keep decimals. let result = Float(a) / Float(b) does this correctly.
  3. Final Answer:

    let result = Float(a) / Float(b) -> Option C
  4. Quick Check:

    Convert Ints to Float before dividing [OK]
Quick Trick: Convert Ints to Float before division to keep decimals [OK]
Common Mistakes:
  • Converting after division
  • Using 'as' for type conversion incorrectly
  • Using Double instead of Float when Float needed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes