简体   繁体   English

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

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

I am new in JAVA and I think I have searched all the questions without finding one similar to my question. 我是JAVA的新手,我想我已经搜索了所有问题而没有找到与我的问题类似的问题。

I want to generate random numbers that would give back 4 fixed numbers using Math.random(). 我想生成随机数,使用Math.random()返回4个固定数字。 The numbers that I want to get are: 0, 90. 180 and 270. In other words, I want to 4 numbers with a minimum value of 0 and maximum value of 270 and an increment of 90. 我想得到的数字是:0,90,180和270.换句话说,我想要4个数字,最小值为0,最大值为270,增量为90。

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

Let's break that down. 让我们打破它。 Start with Math.random() , returning a random decimal in the range [0,1). Math.random()开始,返回范围[0,1)中的随机小数。 (Anything between 0 and 0.999999999..., loosely.) (0到0.999999999之间的任何东西......,松散地。)

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

Next, let's truncate the decimal. 接下来,让我们截断小数。

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

Finally, we'll multiiply by 90. 最后,我们将在90岁之前多道次。

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

You'd better create a java.util.Random object and reuse it: 你最好创建一个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