Search code examples
swiftarc4random

Diving the result of an arc4random_unifrom gives me 0


I am trying to create a decimal between 0 and 1 so I am creating an Int between 0 and 10000 then dividing it by 10000 (an Int) to get the decimal.

AtBatResult = Int(arc4random_uniform(UInt32(10000)))

This line of code gives me number which is fine.

AtBatResult = AtBatResult / Int(10000)

When I run this line of code however, the number becomes 0 no matter what. What is happening here? Thanks in advance!


Solution

  • You've declared atBatResult to be an Int. You can't assign a decimal value to it. And you are doing integer division.

    You need a Double variable and you need to do decimal division.

    Here's one way:

    let atBatResult = Int(arc4random_uniform(UInt32(10000)))
    let finalResult = Double(atBatResult) / 10000
    

    Or you can do:

    let atBatResult = Double(arc4random_uniform(UInt32(10000))) / 10000
    

    This will make atBatResult a Double instead of an Int.

    FYI - it is standard naming convention to start method and variable names with lowercase letters. Class names start with uppercase.