You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:10:17