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?

7
  • 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, 2018 at 15:40
  • 1
    Swift did assign the right type to x, an Int divided by an Int is an Int
    – dan
    Mar 12, 2018 at 15:41
  • 1
    Swift is smart enough. You are doing Int math so x is an Int.
    – rmaddy
    Mar 12, 2018 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, 2018 at 15:42
  • I updated my question now. Thanks.
    – Leem
    Mar 12, 2018 at 15:43

3 Answers 3

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)
0
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

0

Ok then you just need to do:

var b : Int = 10
let c = (Double(b) * 0.75)
let restult = ceil(c)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.