【发布时间】:2021-02-10 11:31:51
【问题描述】:
我正在r 中构建一个函数,它接受 2 个参数并使用勾股定理计算三角形的缺失边。我已经做到了,如果不满足某些条件,就会出现停止消息。例如,第一个停止消息检查参数是否为数字。我的麻烦是如果参数c 小于a 或b,则显示消息。当c=a 或c=b 时,输出为0。当c<a 或c<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
【问题讨论】:
-
我将停在
!is.null(b) & !is.null(a) >= !is.null(c)。首先,不要在if语句中使用&(单个),您应该使用&&。其次,您在评论中的措辞是 “a 或 b 大于或等于 c”,这根本不是该代码正在检查的内容。!is.null(.)将返回logical,因此该表达式不检查标量大小,只是 存在。
标签: r pythagorean