Bezi
Bezi

Reputation: 57

Division operator not working as expected (swift)

I need to calculate the probability of something, and the division operator is not working at all and it just return zero. I can't understand the problem because I tried other operators(*,+,-) and they all work completely fine and return true results.

here is the code:

   Button(action: {

                    self.winner2 = self.diceNames.randomElement()!
                    self.winner1 = self.diceNames.randomElement()!
                    self.rollCount += 1

                    if self.winner1 == self.winner2  {
                        self.pair = self.pairDice
                        self.pairCount += 1
                    }else{
                        self.pair = ""
                    }

                    self.pairChance = Double(self.pairCount / self.rollCount)*100
                    print("\(self.pairChance)")
                })

Upvotes: 1

Views: 405

Answers (1)

Mureinik
Mureinik

Reputation: 312136

You're dividing two integers, so integer division is used. To avoid this, you could explicitly cast the operands to Doubles:

self.pairChance = Double(self.pairCount) / Double(self.rollCount) * 100.0

Upvotes: 4

Related Questions