首页 > 解决方案 > 使用体重和身高计算 BMI,并使用 if else 语句打印用户是否超重、健康或体重不足,不断出现错误

问题描述

我不断收到此错误无法将“String”类型的返回表达式转换为“Double”类型的快速错误

我不知道该尝试什么

import UIKit

func calculateBmi (mass : Double, height: Double) -> Double
{
    let bmi = mass / (height * 2)

if (bmi > 25)
{
    return ("Your bmi is \(bmi) therefore you are overweight")
}
else if (bmi >= 18.5 && bmi < 25)
{
    return ("Your bmi is \(bmi) therefore you are of normal weight")
}
else
{
    return ("Your bmi is \(bmi) therefore you are underweight")
}

}

print(calculateBmi(mass: 75, height: 1.55448))

这是我不断收到的错误无法将“String”类型的返回表达式转换为“Double”类型的快速错误

标签: swift

解决方案


不好意思,大家已经很清楚地回答了你的问题,但是我想指出,计算BMI的公式是体重/(身高*身高),而不是(身高*2)。高度应该是平方的,而不是乘以 2。也许这会对您的代码有所帮助。

但是,如果您愿意,可以使用该pow功能

let bmi = mass / pow(height, 2)

推荐阅读