You need to enable JavaScript to run this app. 在条件函数中使用return实现JavaScript两个骰子函数的输出值对比
优惠活动
大模型
产品
解决方案
定价
更多

在条件函数中使用return实现JavaScript两个骰子函数的输出值对比

问题核心原因

  • 你当前的dice1()和dice2()只有控制台打印逻辑,没有return返回数值,JS中没有显式写return的函数默认返回undefined,自然无法做大小比较
  • 你注释里的写法会多次调用骰子函数,每次调用都会生成新的随机值,判断和打印用到的数值完全不匹配,逻辑有误

修改后的完整JS代码

// 给dice1加return返回生成的点数,这里还简化了冗余的分支判断
function dice1() {
  const rdm1 = Math.random()
  let point = Math.floor(rdm1 * 6) + 1
  console.log("this is dice 1 = " + point)
  // 加return返回点数
  return point
}

function dice2() {
  // 注意:这里你用两个Math.random相乘的逻辑会让点数分布不均匀,出小值的概率远高于大值,如果是做公平骰子建议改成和dice1一致的写法
  const rdm2 = Math.random() * Math.random()
  let point = Math.floor(rdm2 * 6) + 1
  console.log("this is dice 2 = " + point)
  // 加return返回点数
  return point
}

// 先把单次调用的结果存到变量里,避免重复调用生成新值
const num1 = dice1()
const num2 = dice2()

if (num1 < num2) {
  console.log( num2 + " is bigger than " + num1);
} else if (num1 > num2) {
  console.log( num1 + " is bigger than " + num2);
} else {
  console.log("两个骰子点数相同,都是" + num1);
}

补充说明

如果需要实现公平的6面骰子,只需要保留Math.random() * 6的逻辑即可,不需要叠加两次随机数相乘,两次相乘的结果会让小于1的概率大幅提升,最终骰子出1的概率会远高于其他点数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:06:07