首页 > 解决方案 > 即使变量被硬编码,BMI 应用程序打印结果也是 0

问题描述

首先感谢所有即将到来的答案。

我是swift编程新手。我正在测试很多东西哈哈。我正在尝试做一个bmi应用程序。我正在使用 print()以检查我的变量的所有值。我无法理解为什么imcvalue 是0. 我错过了什么 ?逻辑是什么?90/32400我试图用商或x/ySquare相同的结果对其进行硬编码。我还在quotien = 0

导入 UIKit

类视图控制器:UIViewController {
    @IBOutlet 弱 var weightTextField:UITextField!
    @IBOutlet 弱变量 heightTextfield:UITextField!
    @IBOutlet 弱变量结果标签:UILabel!

    覆盖 func viewDidLoad() {
        super.viewDidLoad()
        // 在加载视图后做任何额外的设置,通常是从一个 nib。
    }

    覆盖 func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // 处理所有可以重新创建的资源。
    }

    @IBAction func calculateButton(_ sender: Any) {
        imcCalculator()
    }


    func imcCalculator () {
        让 myHeight = Int(heightTextfield.text!)
        让 myWeight = Int(weightTextField.text!)
        让 x = 我的体重!
        让 y = 我的身高!

        //让 imc = Int(Int(x / pow(y, 2)) * 10000)
        让 ySquare = y * y
        让商 = 90 / 32400
        让 imc = (x/ySquare)*10000
        如果 imc > 25 {
            resultLabel.text = "你的 BMI 是 \(imc) 。你超重了"
        }    
        否则如果 imc 18 {
            resultLabel.text = "您的 BMI 为 \(imc)。您的体重正常"
        }
        别的 {
            resultLabel.text = "你的 BMI 是 \(imc) 。你体重过轻"
        }
        打印(x)
        打印(y)
        打印(ySquare)
        打印(商)
        打印(imc)
    }
}

标签: iosswift

解决方案


发生的事情称为截断整数除法。整数除法的结果因语言而异。正如 Swift文档所述:

对于整数类型,除法的任何余数都将被丢弃

这就是为什么let quotien = 90 / 32400会给0结果。

我建议您改用 Doubles,您的代码可能如下所示:

func imcCalculator () {

    guard let myHeight = Double("6"), let myWeight = Double("70") else {
        fatalError("Error in the text fields")
    }

    let x = myWeight
    let y = myHeight

    //let imc =  Int(Int(x / pow(y, 2)) * 10000)
    let ySquare: Double = y * y
    let quotien: Double = 90.0 / 32400.0
    let imc: Double = (myHeight / ySquare) * 10000

    let imcString: String = String(format: "Your BMI is %.2d", imc)

    if imc > 25 {
        resultLabel.text = imcString + " . You are overweight"
    }
    else if imc < 25 && imc > 18 {
        resultLabel.text = imcString + " . You have a normal weight"
    }
    else {
        resultLabel.text = imcString + " . You are underweight"
    }

    print("x =", x)
    print("y =", y)
    print("ySquare =", ySquare)
    print("quotien =", quotien)
    print("imc =", imc)
}

重点是:某种类型的元素之间的算术运算,给出相同类型的结果

因此,例如除以 时12您应该期望结果也是整数。将商的整数部分定义为两个数字相除的结果是一种惯例。1 除以 2(实数除法)得到 0.5,其整数部分为 0。

另一方面,因为 Dividend 和 Divisor 都被推断为 Doubles 1.0/2.00.5如果您没有.0在至少一个之后添加,那么小数部分将被丢弃。

你可以在操场上试试这个:

3/10          //0
3.0/10.0      //0.3
3.0/10        //0.3
3/10.0        //0.3

正如@Martin R所指出的,当股息(分子)为负时,整数除法的结果与欧几里得除法的商不同,因为截断总是向零舍入。这是什么意思:

  • 在整数除法中:(-3)/10 equals 0

  • 在欧几里得除法中:The quotient of (-3)/10 is -1


推荐阅读