我是swift的新手,我正在尝试制作一个解决方程式(线性或二次方程式)的简单应用程序。用户必须输入a,b,c的值(方程式为:ax ^ 2 + bx + c = 0),如果a = 0,则app解决线性方程式,如果a = = 0,app解决二次方程(或告诉它没有解决方案)。
问题是..线性方程式部分工作正常并给出了正确的结果,但应用程序给出了二次方程的错误结果! 例如,如果a = 4,b = 12,c = 8,结果应为x1 = - 1,x2 = -2,但我在应用程序中获得的解是x1 = -16.0,x2 = -32.0
x1 / x2似乎是正确的(0.5),但结果完全错误
这是我写的代码
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var EnterA: UITextField!
@IBOutlet weak var EnterB: UITextField!
@IBOutlet weak var EnterC: UITextField!
@IBOutlet weak var LabelYourEquation: UILabel! // gonna deal with this later
@IBOutlet weak var Button: UIButton!
@IBOutlet weak var LabelX1: UILabel!
@IBOutlet weak var LabelX2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var a = Double()
var b = Double()
var c = Double()
var delta = Double()
var x1 = Double()
var x2 = Double()
var linearEquation = Bool()
var quadraticEquation = Bool()
func checkEquation() {
if a == 0 {
linearEquation = true
quadraticEquation = false
} else if a != 0 {
quadraticEquation = true
linearEquation = false
}
}
func linearEquationResolution() -> Double {
x1 = -c / b
LabelX2.hidden = true
LabelX1.text = "x = \(x1)"
return x1
}
func Delta() -> Double {
delta = (b * b) - (4 * a * c)
return delta
}
func quadraticEquationResolution() {
if delta >= 0 {
x1 = ( -b + sqrt(delta)) / 2*a
x2 = ( -b - sqrt(delta)) / 2*a
LabelX1.hidden = false
LabelX2.hidden = false
LabelX1.text = "x1 = \(x1)"
LabelX2.text = "x2 = \(x2)"
} else if delta < 0 {
LabelX1.text = "The equation has no solution"
LabelX2.hidden = true
}
}
func solveIt() {
if linearEquation == true {
linearEquationResolution()
} else if quadraticEquation == true {
Delta()
quadraticEquationResolution()
}
}
func Hide() {
LabelX2.hidden = true
LabelX1.hidden = true
}
@IBAction func SolveItAction(sender: AnyObject) {
a = Double(EnterA.text!)!
b = Double(EnterB.text!)!
c = Double(EnterC.text!)!
checkEquation()
solveIt()
}
}
有什么想法吗?我做错了什么?
答案 0 :(得分:1)
您错误地乘以a
而非划分
( -b + sqrt(delta)) / (2*a)