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

如何让Math.random()生成的card1int取值范围为2到21?

解决Math.random()生成指定范围整数的问题

要让card1int的取值范围为2到21(包含两端),可以通过调整Math.random()的计算逻辑实现,具体修改如下:

问题分析

原代码中Math.random()*21生成的是[0, 21)区间的浮点数,经过Math.round()后,可能得到0、1这类小于2的数值,不符合需求。我们需要直接生成[2,21]的整数。

修改方案

利用Math.random()生成[0,1)区间的特性,通过以下公式计算目标范围的整数:

// 公式:(int)(Math.random() * (最大值 - 最小值 + 1)) + 最小值
int card1int = (int)(Math.random() * 20) + 2;
  • Math.random() * 20生成[0,20)的浮点数,强制转换为int后得到0到19的整数
  • 加上2后,范围变为2到21,正好符合需求

修改后的完整代码

Cards card1 = new Cards();
// 无需再使用cardsnumber变量,直接计算目标整数
int card1int = (int)(Math.random() * 20) + 2;

如果必须保留cardsnumber变量,也可以这样写:

Cards card1 = new Cards();
card1.cardsnumber = Math.random() * 20 + 2;
int card1int = (int) Math.floor(card1.cardsnumber);

这里用Math.floor()确保向下取整,避免round()可能带来的边界值偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:48:41