我收到第 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 行

解决方法

您需要 * 表示产品,例如

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...