-1
enter code here
fn = function(a, b, c) {
if ((b^2 - 4ac) > 0) {
root1 = ((-b) + sqrt((b^2) - 4 a c)) / (2 * a) 
root2 = ((-b) - sqrt((b^2) - 4 a c)) / (2 * a)
print(root1)
print(root2)
} else if (b*2 -4a*c == 0) {
root = -b / (2*a)
print(root)
} else {
print("There are no real roots.")
}
}

unexpected token 'ac' line 2

unexpected token 'a' line 3

unexpected token 'a' line 4

unexpected token 'a' '*' line 7

KevoK
  • 1
  • 2
  • 1
    You need to use explicit arithmetic operators. For example `4ac` should be `4*a*c`. Also I would be cautious about using the name `c` since in base R this is the commonly used combine function. See `?c`. – LMc Mar 10 '21 at 21:11

1 Answers1

1

You need * for product, e.g.,

fn <- function(a, b, c) {
  if ((b^2 - 4 * a * c) > 0) {
    root1 <- ((-b) + sqrt((b^2) - 4 * a * c)) / (2 * a)
    root2 <- ((-b) - sqrt((b^2) - 4 * a * c)) / (2 * a)
    print(root1)
    print(root2)
  } else if (b * 2 - 4 * a * c == 0) {
    root <- -b / (2 * a)
    print(root)
  } else {
    print("There are no real roots.")
  }
}

such that

> fn(1, -2, 1)
[1] "There are no real roots."
> fn(1,1,0)
[1] 0
[1] -1
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81