gpt4 book ai didi

ios - 在我的方程求解程序中,输入 nil 值会使应用程序崩溃

转载 作者:行者123 更新时间:2023-11-29 00:50:51 25 4
gpt4 key购买 nike

我制作了一个求解二次方程的应用程序(只是想看看我是否可以),但是,如果用户不小心为其中一个槽输入任何值,我不希望该应用程序崩溃。请帮忙。

 @IBAction func solveButton(sender: AnyObject) {

let a:Double! = Double(textFieldA.text!) // textfieldA is UITextField
let b:Double! = Double(textFieldB.text!) // textfieldB is UITextField
let c:Double! = Double(textFieldC.text!) // textFieldC is UITextField

// This is for if the a value is nil
if a == nil && b == nil && c == nil{

errorTextField.text = "Please do not leave an empty value, all quadratic equations must have 3 values!"
answerLabel.text = " "

answerLabelNegative.text = " "
whatEquation.text = " "
return

} else {

let a:Double! = Double(textFieldA.text!) // textfieldA is UITextField
let b:Double! = Double(textFieldB.text!) // textfieldB is UITextField
let c:Double! = Double(textFieldC.text!) // textFieldC is UITextField
let x:Double = (b * b)
let y:Double = -4 * a * c //Here I get EXC_BAD_INSTRUCTION error
let xy:Double = x + y
let az:Double = sqrt(xy)
let finalTopPlus:Double = -b + az
let finalTopMinus:Double = -b - az
let aTwo:Double = 2 * a
let finalEquationPositive:Double = finalTopPlus / aTwo
let finalEquationNegative:Double = finalTopMinus / aTwo

answerLabel.text = "Positive x = \(finalEquationPositive)"
answerLabelNegative.text = "Negative x = \(finalEquationNegative)"

let aValue = a < 0 ? "-" : " "
let bValue = b < 0 ? " " : "+"
let cValue = c < 0 ? " " : "+"
whatEquation.text = "Equation: \(aValue) \(a)x² \(bValue) \(b)x \(cValue) \(c)"
}

最佳答案

您的 if 语句检查是否所有值都为 nil。您想查看其中是否有nil

if更改为:

if a == nil || b == nil || c == nil {

我不会使用 Swift 进行编程,但我的印象是,您应该进行许多其他改进来验证值不是 nil

关于ios - 在我的方程求解程序中,输入 nil 值会使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com