简体   繁体   English

如何生成一定范围内的随机数

[英]How do I generate random numbers within a range

computerTotal = (int) Math.ceil(Math.random() * 21);

Can someone show me how to get 16 - 21 random number I keep getting errors when i try to implement the Math.floor function... As you can see i'm not very good at putting functions within functions. 有人可以告诉我如何获取16-21个随机数吗?当我尝试实现Math.floor函数时,我总是出错。正如您所看到的,我不太擅长将函数放入函数中。

Many Thanks! 非常感谢!

If Java, use the Random Class. 如果是Java,请使用Random类。

Random r = new Random();
int myRand = 16+ r.nextInt(6); //16+[0-6) = 16-21

For creating random numbers between (including) min and max , you can do this: 要创建介于(包括) minmax之间的随机数,可以执行以下操作:

Math.floor(Math.random() * (max - min + 1)) + min

Edit: The JAVA tag was added only after I suggested this; 编辑:仅在我建议之后才添加JAVA标记; before it had no tags hinting at a specific language at all – so that there might be better/already implemented methods for this in language X is well possible. 之前它根本没有标签暗示一种特定的语言,因此很有可能已经有了使用X语言的更好/已经实现的方法。 This is a very generic approach. 这是一种非常通用的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM