0

我想为毕达哥拉斯定理编写 R 代码。

毕达哥拉斯定理指出,斜边(直角的对边)的平方等于其他两条边的平方和。

(边A)^2+(边B)^2=斜边^2

现在我编写了如下的 R 代码:

pythag<-function(sidea,sideb){
if (sidea>=0&sideb>=0)
hypoteneuse=sqrt(sidea^2+sideb^2)
else if (sidea<0|sideb<0)
hypoteneuse<-"Values Need to be Positive"
else if (!is.vector(x))
hypoteneuse<-"I need numeric values to make this work"
print(hypoteneuse)
}
pythag(4,5)
pythag("A","B")
pythag(-4,-5)

在 pythag(4,5) 的情况下没关系,pythag(-4,-5) 也给出评论“值需要为正”。

但是在 pythag("A","B") 的情况下,我想评论“我需要数值来完成这项工作”,但不幸的是我的代码不适用于此。

4

3 回答 3

3

你可以这样尝试:

get_hypotenuse_length <- function(height, base)
{
  sides <- c(height, base)
  if(any(sides < 0))
  {
    message("sides must be positive")
  } else if(!is.numeric(x = sides))
  {
    message("sides can not be non-numeric")
  } else
  {
    sqrt(x = sum(sides ^ 2))
  }
}
于 2019-07-28T12:16:47.900 回答
1

这是一个带注释的版本。它正在创建接受值ab计算的函数c。它首先测试值是否为数字,如果它们不是数字,它将打印您的错误消息,否则它将忽略那些大括号内的内容并继续下一个测试。第二个测试是检查两者是否都大于零(看到三角形不能有长度为零或负长度的边)。如果它满足两个都 > 0 的条件,那么它将计算c,如果不是,它将给出错误说明存在负值。

# Feed it the values a and b (length of the two sides)
pythag <- function(a,b){

  # Test that both are numeric - return error if either is not numeric
  if(is.numeric(a) == FALSE | is.numeric(b) == FALSE){
    return('I need numeric values to make this work')}

  # Test that both are positive - return length of hypoteneuese if true...
  if(a > 0 & b > 0){
    return(sqrt((a^2)+(b^2)))
  }else{

    # ... give an error either is not positive
    return('Values Need to be Positive')  
  }

}

这是一个更精简的版本:

pythag <- function(a,b){
  if(is.numeric(a) == FALSE | is.numeric(b) == FALSE){return('I need numeric values to make this work')}
  if(a > 0 & b > 0){return(sqrt((a^2)+(b^2)))}
  else{return('Values Need to be Positive')}
  }

这就是您的示例返回的内容:

> pythag(4,5)
[1] 6.403124
> pythag("A","B")
[1] "I need numeric values to make this work"
> pythag(-4,-5)
[1] "Values Need to be Positive"
于 2019-07-28T12:19:42.503 回答
0

如果x = c("sideA", "sideB"),那么它仍然是一个向量,因此您的测试is.vector(x)将返回true

> is.vector(x)
[1] TRUE

但是你想测试它是否是数字,所以如果它是数字:

> is.numeric(x)
[1] FALSE
于 2019-07-28T11:59:11.227 回答