我制作了一个求解二次方程的应用程序(只是看看我是否可以),但是,如果用户不小心为其中一个插槽输入了任何值,我不希望应用程序崩溃。请帮忙。
@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)"
}