如何显示错误消息并在R中终止

时间:2017-04-02 17:07:52

标签: r

s <- 2
t <- 1
a <- s^2-t^2
b <- 2*s*t
c <- s^2 + t^2

 function(coeff){ 
        a <- coeff[1]
        b <- coeff[2]
        c <- coeff[3]
        d <- b^2 -(4*a*c)
        cat("The discriminant is:",d,"\n")
        if(d<0) cat("There are no real roots. ","\n")
      if (d>=0){
          root1<-(-b+sqrt(d))/(2*a)
          root2 <-(-b+sqrt(d))/(2*a)
          cat("root1: ",root1,"\n")
          cat("root1: ",root2,"\n")
          }

    }

所以我该如何解决?

当a = 0时,我想显示“无效号码”之类的错误消息,然后终止

1 个答案:

答案 0 :(得分:1)

您可以使用stop()

temp <- function(coeff){ 
    a <- coeff[1]
    b <- coeff[2]
    c <- coeff[3]
    d <- b^2 -(4*a*c)
    if( a < 0) stop("Invalid Number")
    cat("The discriminant is:",d,"\n")
    if(d<0) cat("There are no real roots. ","\n")
    if (d>=0){
        root1<-(-b+sqrt(d))/(2*a)
        root2 <-(-b+sqrt(d))/(2*a)
        cat("root1: ",root1,"\n")
        cat("root1: ",root2,"\n")
    }

}