0

I try to use swift code to calculate 10 * 75% = 7.5

var b : Int = 10
var a : Int = 75
// result x is 0
var x = b * (a / 100) 

However the result is zero. How to get 7.5 result without changing the type and value of a and b?

UPDATE:

I got it right by:

 var x: Double = (Double(b) * (Double(a) / 100)) // x is 7.5

Now, how can I round it to 8 as a Int type?

Leem
  • 15,772
  • 32
  • 101
  • 149
  • But I didn't claim x is an integer type. I expected swift is smart to assign the right type to x – Leem Mar 12 '18 at 15:40
  • 1
    Swift did assign the right type to x, an `Int` divided by an `Int` is an `Int` – dan Mar 12 '18 at 15:41
  • 1
    Swift is smart enough. You are doing `Int` math so `x` is an `Int`. – rmaddy Mar 12 '18 at 15:41
  • BTW - your use of `: Int` for `a` and `b` is redundant. `var b = 10` will automatically make `b` the type `Int`. – rmaddy Mar 12 '18 at 15:42
  • I updated my question now. Thanks. – Leem Mar 12 '18 at 15:43
  • Not being serious, but this fulfills the requirements: `var x = b * a / 100; if (b * a % 100) >= 50 { x += 1 }` – vadian Mar 12 '18 at 16:09
  • It is simple. In the same way you converted a and b to Double, convert x to an int with ` print(Int(x)) ` – Michael Mar 12 '18 at 16:15
  • In the future, rather than editing your question to include an answer, just [post your own answer to your own question](https://stackoverflow.com/help/self-answer). I'd also suggest that you up-vote answers that helped you and [accept the answer that best answered the question](https://stackoverflow.com/help/someone-answers). – Rob Mar 12 '18 at 16:53

3 Answers3

0

You're using integer (i.e. whole number) arithmetic, when what you want is floating-point arithmetic. Change one of the types to Float, and Swift will figure out that x is also a Float.

var b : Int = 10
var a : Int = 75
var x = Float(b) * (Float(a) / 100.0) // now x is a Float (.75)
rmaddy
  • 307,833
  • 40
  • 508
  • 550
NRitH
  • 12,737
  • 4
  • 41
  • 43
0

Ok then you just need to do:

var b : Int = 10
let c = (Double(b) * 0.75)
let restult = ceil(c)
Norman G
  • 759
  • 8
  • 17
0

For doing arithmetic in Swift, both sides of the equation must be using the same type. Try using this code:

let b = 10.0
let a = 75.0
let x = b * (a / 100.0
print(x)

7.5

To make it round up, use the built in ceil function

print(ceil(x))

8.0

Scriptable
  • 18,734
  • 5
  • 56
  • 68