繁体   English   中英

如何使用Math.random生成随机数给出固定结果

[英]How to generate random numbers the give fixed results using Math.random

我是JAVA的新手,我想我已经搜索了所有问题而没有找到与我的问题类似的问题。

我想生成随机数,使用Math.random()返回4个固定数字。 我想得到的数字是:0,90,180和270.换句话说,我想要4个数字,最小值为0,最大值为270,增量为90。

int rand = ((int)(Math.random()*4)) * 90;

让我们打破它。 Math.random()开始,返回范围[0,1)中的随机小数。 (0到0.999999999之间的任何东西......,松散地。)

Math.random()*4 //Gives a random decimal between 0 and 4 (excluding 4)

接下来,让我们截断小数。

(int)(Math.random()*4) //Truncates the decimal, resulting in a random int: 0, 1, 2, or 3

最后,我们将在90岁之前多道次。

int rand = ((int)(Math.random()*4)) * 90; //0*90=0, 1*90=90, 2*90=180, or 3*90=270

你最好创建一个java.util.Random对象并重用它:

   Random r = new java.util.Random();
   ...
   int x = r.nextInt(4)*90;

暂无
暂无

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

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