首页 > 解决方案 > 这个 R 函数导出每个形状的面积有什么问题?

问题描述

area<-function(...){
 x<-c(...)
 cat("It is area of: ", x[1])
 if (x[1]=="triangle"|1) {
   cat("the baseline is: ", x[2])
   cat("the height is: ", x[3])
   cat("Area equals to ",(x[2]*x[3])/2)
 } 
 if (x[1]=="square"|2) {
   cat("the baseline is ", x[2])
   cat("the height is: ", x[3])
   cat("the area is ",x[2]*x[3])
 }
}

area(1,4,2)

这个功能有什么问题?我正在尝试在这里创建一个函数,它应该显示 R 中三角形、正方形区域的结果。请帮助我解决错误。

标签: rfunction

解决方案


这里有一些可以改进的地方。主要问题是您的语法错误;你不能这样做if(x[1] == "square"|2)。你需要做类似的事情if(x[1] == "square" | x[1] == 2)。然而,即使这样也是有问题的。如果您的第一个参数是字符串(例如,如果您调用了该行,area("triangle", 2, 3)则该c(...)行会将 3 个条目转换为字符向量,因此数学运算将不起作用。

您的代码中也有不必要的重复,这可能是错误的来源。

最后,您的cat调用没有换行符,这会使输出变得混乱。

将这些更改放在一起,这是该功能如何工作的可重现示例:

area <- function(...){
 x <- c(...)
 area <- x[2] * x[3]
 if (x[1] == 1)  area <- area / 2
 cat("It is area of:", c("triangle", "square")[x[1]])
 cat("\nThe baseline is:", x[2])
 cat("\nThe height is:", x[3])
 cat("\nArea equals to", area)
}

area(1, 4, 2)
#> It is area of: triangle
#> The baseline is: 4
#> The height is: 2
#> Area equals to 4

一种更好、更惯用的方法是使用命名参数而不是c(...). 这使得保持正确的类型变得更加容易。例如,以下函数更容易阅读和理解,并允许将数字或字符串作为第一个参数传递:

area <- function(shape, base, height){
 if(is.numeric(shape)) shape <- c("triangle", "square")[shape]
 area <- base * height
 if (shape == "triangle")  area <- area / 2
 cat("It is area of:", shape)
 cat("\nThe baseline is:", base)
 cat("\nThe height is:", height)
 cat("\nArea equals to", area)
}

area(1, 4, 2)
#> It is area of: triangle
#> The baseline is: 4
#> The height is: 2
#> Area equals to 4

area("triangle", 4, 2)
#> It is area of: triangle
#> The baseline is: 4
#> The height is: 2
#> Area equals to 4

reprex 包(v0.3.0)于 2020 年 12 月 13 日创建


推荐阅读