Quadratic Formula -Swift Lesson Project

Hello,

I am new to coding. I am trying my best. Here is my code for the quadratic formula. It is not working. Can someone explain what is wrong?
var a: Double = 2.0

var b: Double = 5.0

var c: Double = 3.0

// 2x^2 + 5x + 3 = 0

var root1: Double

var root2: Double

root1 = -b + (b * b - 4 * a * c).squareRoot() ) / 2 * a

root2 = -b - (b * b - 4 * a * c).squareRoot() ) / 2 * a

print(“Root 1 is (root1).”)

print(“Root 2 is (root2).”)

The errors I am getting are:

12346791011128513
var a: Double = 2.0
var b: Double = 5.0
var c: Double = 3.0
// 2x^2 + 5x + 3 = 0

var root1: Double
var root2: Double

root1 = -b + (b * b - 4 * a * c).squareRoot() ) / 2 * a
root2 = -b - (b * b - 4 * a * c).squareRoot() ) / 2 * a

print(“Root 1 is (root1).”)
print(“Root 2 is (root2).”)
note: I am using reversed / in the print. But for some reason it is not showing in the forum text.
Save

Output:
Quadratic.swift:9:46: error: consecutive statements on a line must be separated by ‘;’
root1 = -b + (b * b - 4 * a * c).squareRoot() ) / 2 * a
^
;
Quadratic.swift:9:47: error: expected expression
root1 = -b + (b * b - 4 * a * c).squareRoot() ) / 2 * a
^

Two issues:

  • You are missing an opening parenthesis in root1 and root2

  • The denominator should be wrapped in parentheses. Otherwise, the order of operations will give a different result than expected.

// Your code:
root1 = -b + (b * b - 4 * a * c).squareRoot() ) / 2 * a

// It should be:
root1 = (-b + (b * b - 4 * a * c).squareRoot() ) / (2 * a)

// Order of operations
x = 8 / 2 * 2   // x will be 8

x = 8 / (2 * 2)  // x will be 2

Also, for formatting code in posts, see

1 Like