R函数求助:胜负判定函数报错及输出逻辑异常问题
修复R胜负判定函数的问题
问题根源
- 函数开头的
score_A<-()和score_B<-()直接覆盖了传入的参数值,后续判断用的是空值,这是导致输出异常的核心原因。 - 逻辑分支顺序错误,最后一个
else if永远不会触发,因为前三个条件已经覆盖了所有数值比较的可能(等于、小于、大于)。另外该条件的语法也有误,正确判断两队得分均≥5的写法是score_A >=5 & score_B >=5,但根据你的需求,这个分支可能属于多余项。
修复后的基础版代码
score <- function(score_A, score_B) { if (score_A == score_B) { print("TIE GAME") } else if (score_A < score_B) { print("Team B wins") } else { print("Team A wins") } }
验证示例
- 执行
score(3, 3),输出[1] "TIE GAME" - 执行
score(2, 5),输出[1] "Team B wins" - 执行
score(7, 4),输出[1] "Team A wins"
若需保留“两队得分均≥5则无胜者”逻辑的版本
score <- function(score_A, score_B) { if (score_A >=5 & score_B >=5) { print("No winner") } else if (score_A == score_B) { print("TIE GAME") } else if (score_A < score_B) { print("Team B wins") } else { print("Team A wins") } }
内容的提问来源于stack exchange,提问作者Emily
相关产品推荐
相关产品推荐

