tommsyeah - 1 year ago 142
Swift Question

# Swift - Quadratic equation solver gives wrong results?

I'm new to swift and I'm trying to make a little simple app that solves equations (linear or quadratic ones). The user has to enter the values for a,b,c (the equation is: ax^2 + bx + c = 0) and, if a = 0, the app solves the linear equation, if a != 0, the app solves the quadratic equation (or tells it has no solution).

The problem is.. the linear equations part works just fine and gives the right results, but the app gives wrong results for the quadratic equations!
For example if a = 4, b = 12, c = 8, the result should be x1 = - 1, x2 = -2, but the solutions I get here in the app are x1 = -16.0, x2 = -32.0

x1/x2 seems to be right (0.5) but the results are completely wrong

This is the code I wrote

``````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()

}

}
``````

Any ideas? What did I do wrong?

Answer Source

You erroneously multiply by `a` instead of dividing

``````( -b + sqrt(delta)) / (2*a)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download