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

如何让R语言随机生成D20数值并根据数值输出对应提示文本

修正R语言D20骰子模拟代码

原代码的问题在于多个独立的ifelse会逐一执行,导致不符合预期的输出(比如掷出15时,第二个ifelse输出正确提示,但第三个ifelse会输出错误的'reroll'),同时条件判断可以简化。以下是优化后的实现:

方法1:嵌套ifelse

d20roll <- sample(1:20, 1)
d20roll

result <- ifelse(d20roll > 18, 
                 'Summon a dragon', 
                 ifelse(d20roll > 12, 
                        'Cast haste on the nearest archer', 
                        'Go directly to jail, do not pass go'))
result

方法2:基础if-else结构

如果更看重可读性,也可以用基础的分支结构:

d20roll <- sample(1:20, 1)
d20roll

if (d20roll > 18) {
  cat('Summon a dragon\n')
} else if (d20roll > 12) {
  cat('Cast haste on the nearest archer\n')
} else {
  cat('Go directly to jail, do not pass go\n')
}

方法3:使用dplyr::case_when(需先加载dplyr包)

library(dplyr)

d20roll <- sample(1:20, 1)
d20roll

result <- case_when(
  d20roll > 18 ~ 'Summon a dragon',
  d20roll > 12 ~ 'Cast haste on the nearest archer',
  TRUE ~ 'Go directly to jail, do not pass go'
)
result

说明

  • 所有方法都会先输出掷出的点数,再输出对应的提示文本
  • 条件判断简化:d20roll >18已经覆盖19、20(因为样本范围是1-20),无需额外判断<21
  • 确保每个点数都对应唯一的提示,不会出现多余的'reroll'输出

内容的提问来源于stack exchange,提问作者Michael Harmon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:02:41