如果 "c" 必须大于 "a" 或 "b" 的毕达哥拉斯函数语句

If statement for pythagorean function where "c" has to be greater than "a" or "b"

我正在 r 中构建一个函数,它接受 2 个参数并使用勾股定理计算三角形的缺失边。我已经做到了,如果不满足某些条件,就会出现停止消息。例如,第一个停止消息检查参数是否为数字。如果参数 c 小于 ab,我的问题是让消息出现。当 c=ac=b 时,输出为 0。当 c<ac<b 时,输出为 NaN。除此之外,它工作得很好。我弄乱了那段代码并被卡住了。有什么建议吗?

pythagorean <- function( a = NULL, b = NULL, c = NULL){
sides <- c(a, b, c)                              

#stop message will appear if arguments are not numeric
if(!is.numeric(sides)){                         
  stop("Arguments must be numeric")
}


#stop message will appear if the amount of arguments is not 2 
if(length(sides) <2){                           
  stop("Must provide 2 arguments")
}else if(length(sides) >2){                    
  stop("Must provide 2 arguments")
}


#if a or b are greater than or equal c, it will not be calculated
#otherwise, the missing value will be calculated
if(!is.null(b) & !is.null(a) >= !is.null(c)){                           
  stop("c must be greater than a")
}else if(!is.null(a) & !is.null(b) >= !is.null(c)){                           
  stop("c must be greater than b")
}else

  #calculate c if a and b are given
  if(is.null(c)){   
    sqrt(a^2 + b^2)
  
  #calculate b if a and c are given
  }else if (is.null(a)){    
    sqrt((c^2) - (b^2))
  
  #calculate a if b and c are given
  }else if (is.null(b)){   
    sqrt((c^2) - (a^2))
  }
}
#samples testing the code
pythagorean(a=5, c=5) #c=a
pythagorean(b=3, c=3) #c=b
pythagorean(a=8, c=4) #c<b
pythagorean(a=9, c=6) #c<a
pythagorean(a=5, c=10) #c>a
pythagorean(b=3, c=12) #c>b
pythagorean(a=3, b=4) #calculating for c
pythagorean(b=4, c=5) #calculating for a
pythagorean(a=3, c=5) #calculating for b
pythagorean(a=-3, c=5) #takes negative numbers
#output
[1] 0
[1] 0
NaNs produced[1] NaN
NaNs produced[1] NaN
[1] 8.660254
[1] 11.61895
[1] 5
[1] 3
[1] 4
[1] 4

使用标量运算符 (&&) 在这里会有帮助。

 #...
 if(!is.null(a) && !is.null(c) && c <= a){                           
    stop("c must be greater than a")
  }else if(!is.null(b) && !is.null(c) && c <= b){                           
    stop("c must be greater than b")
  }else
 #...
 #...
pythagorean(a=5, c=5) #c=a
#Error in pythagorean(a = 5, c = 5) : c must be greater than a
pythagorean(b=3, c=3) #c=b
#Error in pythagorean(b = 3, c = 3) : c must be greater than b
pythagorean(a=8, c=4) #c<b
#Error in pythagorean(a = 8, c = 4) : c must be greater than a
pythagorean(a=9, c=6) #c<a
#Error in pythagorean(a = 9, c = 6) : c must be greater than a
pythagorean(a=5, c=10) #c>a
#[1] 8.660254
pythagorean(b=3, c=12) #c>b
#[1] 11.61895
pythagorean(a=3, b=4) #calculating for c
#[1] 5
pythagorean(b=4, c=5) #calculating for a
#[1] 3
pythagorean(a=3, c=5) #calculating for b
#[1] 4
pythagorean(a=-3, c=5) #takes negative numbers
#[1] 4