首页 > 解决方案 > 第 2、3、4 和 7 行出现意外令牌错误

问题描述

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.")
}
}

意外令牌“ac”第 2 行

意外标记“a”第 3 行

意外标记“a”第 4 行

意外标记“a”“*”第 7 行

标签: runexpected-token

解决方案


您需要*产品,例如,

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.")
  }
}

这样

> fn(1, -2, 1)
[1] "There are no real roots."
> fn(1,1,0)
[1] 0
[1] -1

推荐阅读