Swift - What is the output: mixing int and double?

Question

What is the output of the following code?

var weight = 154
var height = 66.9
var BMI = (weight / pow(height,2)) * 703.06957964
print(BMI)


Click to view the answer

The compiler generates an error.
weight  is inferred to be of type  Int.
It will cause the error when using it to multiply other Double  values.

Note

The first way to fix this is to ensure that you assign a floating-point value to weight so that the compiler can infer it to be of type Double :

Demo

var weight = 154.0
var height = 66.9
var BMI = (weight / pow(height,2)) * 703.06957964
print(BMI)// w w w  .j  a v a 2  s.co  m

The second approach is to explicitly declare weight as a Double:

Demo

var weight:Double  = 154
var height = 66.9
var BMI = (weight / pow(height,2)) * 703.06957964
print(BMI)//from   www.j ava2 s  . c o  m

The third approach is to explicitly perform a cast on weight and height when performing the calculations:

Demo

var weight = 154
var height = 66.9
var BMI =  (Double (weight) / pow(Double (height),2)) * 703.06957964
print(BMI)//w w w  .  j  a  va 2 s . co  m

Related Exercise