两个UITextField的平方根

时间:2018-03-26 06:45:24

标签: swift uitextfield

我找不到从两个UITextField获取数据并在另一个中显示根值的方法。这是我有多远:

@IBAction func squareRoot(_ sender: Any){
       cValue.text = String(Double(cValue.text!)! * Double(cValue.text!)!)
       dValue.text = String(Double(dValue.text!)! * Double(dValue.text!)!)
       var theSquare = dValue.text! + cValue.text!
       theRootValue.text! =  sqrt(theSquare)

1 个答案:

答案 0 :(得分:1)

像这样使用:

func getRootValue() {
        if let cText = cValue.text, let dText = dValue.text {
            if let doubleC = Double(cText), let doubleD = Double(dText) {
                let theSquare = sqrt((doubleC * doubleC) + (doubleD * doubleD))
                rootValue.text = "\(theSquare)"
            }
        }
    }

    @IBAction func buttonPressed(_ sender: UIButton) {
        getRootValue()
    }   

在你的版本中,你取字符串的根 的更新
根据评论你需要写下一个方法:

func getRoofArea() {
        if let rootText = rootValue.text, let rootDouble = Double(rootText), let eText = eValue.text, let eDouble = Double(eText) {
            roofArea.text = "\(eDouble * rootDouble * 2)"
        }
    }

    @IBAction func secondButtonPressed(_ sender: UIButton) {
        getRoofArea()
    }   

如果你的rootValue.text!= nil,eValue.text!= nil,并且如果它可以转换为Double,则在roofArea.text中你可以看到它的倍数的结果乘以2.
和ScreenShot

Screenshot

有问题吗?