Q: How can I do calculations in swift
I'm making a Quadratic Solver. As shown on the picture, I have value a,b,c. I want to use the formula x=(-b+-√(b^2-4ac))/2a to solve it. I would like the result to be shown at x1 and x2. What should I write in the code?
My codes are below
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var a: UITextField!
@IBOutlet weak var b: UITextField!
@IBOutlet weak var c: UITextField!
@IBAction func solve(_ sender: AnyObject) {
equation.text = "\(a.text!) x^2 + \(b.text!) x + \(c.text!) = 0"
x1.text = (-b+(√b^-4ac))/2a
x2.text = (-b-(√b^-4ac))/2a
}
@IBOutlet weak var equation: UILabel!
@IBOutlet weak var x1: UILabel!
@IBOutlet weak var x2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
MacBook Pro, iOS 10, Xcode
Posted on Sep 22, 2016 4:47 AM
It would be nice if you said what error you got.
You seem to be confusing text with floats. You need to convert a,b and c to doubles to calculate with them and then convert the expression back into a string to print it.
Posted on Sep 25, 2016 6:48 PM
