SugarmanZhu

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

Screen Shot 2016-09-22 at 7.26.05 PM.png

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

Close

Q: How can I do calculations in swift

  • All replies
  • Helpful answers