繁体   English   中英

Xcode“无法将类型为'String'的返回表达式转换为类型为'Float'的返回值”

[英]Xcode “Cannot convert return expression of type 'String' to return type 'Float'”

我正在尝试创建一个BMI计算器,该计算器将用户的身高和体重作为输入,然后计算其BMI; 从那里开始,它使用一系列if-else语句向用户返回一条消息,指出用户是否健康/体重过重/体重不足。 我可以让程序返回计算出的BMI值没有问题; 但是当我合并if-else语句时,出现“无法将类型'String'的返回表达式转换为类型'Float'的返回”错误。

这是我的代码(到目前为止,我只执行了一个if-else语句):

import UIKit

func bodyMassIndex (userHeight : Float, userWeight : Float) -> String {

    let userHeightSquared = (userHeight*userHeight)

    let userWeight = userWeight

    let userBMI = (userWeight/userHeightSquared)

    return userBMI

    if userBMI > 25 {
      return "Overweight"
    } 
}

print(bodyMassIndex (userHeight : 1.82, userWeight: 90.7))

您的逻辑在这里看起来有些混乱:

return userBMI
if userBMI > 25 {
    return "Overweight"
} 

您的功能应该做什么? 返回BMI编号或描述性字符串? (它试图两者都做,并且编译器不满意)

如果我是用户,那么我想同时看到数字关于含义的说明-因此,您需要两个功能:

func bodyMassIndex (userHeight : Float, userWeight : Float) -> String {
  let userHeightSquared = (userHeight*userHeight)
  let userWeight = userWeight
  let userBMI = (userWeight/userHeightSquared)
  return userBMI
}

func bodyMassDiagnosis (bodyMassIndex : Float) {
  if userBMI > 25 {
    return "Overweight"
  }
  return "You're doing fine"
} 

接着:

let bodyMassIndex = bodyMassIndex(height, weight)
let diagnosis = bodyMassDiagnosis(bodyMassIndex)
self.indexLabel.text = "BMI \(bodyMassIndex)"
self.diagnosisLabel.text = diagnosis

您只需userBMIFloatuserBMIString

func bodyMassIndex (userHeight : Float, userWeight : Float) -> String {

    let userHeightSquared = (userHeight*userHeight)

    let userWeight = userWeight

    let userBMI = (userWeight/userHeightSquared)

    return String(userBMI)

    if userBMI > 25 {

        return "Overweight"

    } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM