In todays lecture I covered the basics of functions, conditional statements, comments and printing stuff.
Here is the code I wrote to calculate the BMI of a person.
import UIKit
func calculateBmi(weight: Double, height: Double) -> String {
var finalBmi = weight / (height * height)
let shortBmi = String(format: "%.2f", finalBmi)
if finalBmi > 25 {
return "Your BMI is \(shortBmi) , you are overweight."
} else if finalBmi > 18.5 && finalBmi <= 25 {
return "Your BMI is \(shortBmi) , you have a normal weight."
} else {
return "Your BMI is \(shortBmi) , you are underweight."
}
}
print(calculateBmi(weight: 85, height: 1.8))
The formulae used for calculating the BMI is -: weight(kg) / height(in meters) * height(in meters)
What the code basically does:
- Creates a function which takes weight and height as input. (used double instead of Int, to facilitate use of decimals)
- finalBmi contains the method of calculating BMI
- shortBmi basically restricts the output to 2 decimal places
- If BMI is greater than 25 then return a certain statement to the user, if not then return another statement.
- Finally used print to log the output to the console.