您的位置:首页 > 编程语言 > Java开发

java生成随机数总结

2013-11-27 23:16 393 查看
import java.util.*;

public class RandomDemo{
public static void main(String[] args){

/*
Math.random()的随机数范围为0<=n<1,即:[0,1)
*/
double d1 = Math.random();
System.out.println(d1);
/*
0.13588173801188785
*/

/*
生成4位随机整数
*/
int i4 = (int)(Math.random()*9000)+1000;
System.out.println(i4);
/*
6287
*/

/*
Math取整数的几个方法说明:
Math.floor 向下取整(不大于参数的最大整数 )
Math.ceil 向上取整(不小于参数的最大整数 )
math.round  四舍五入取整(算法为Math.floor(x+0.5))
*/
System.out.println(Math.floor(2.5));
System.out.println(Math.floor(-2.5));
System.out.println(Math.ceil(2.5));
System.out.println(Math.ceil(-2.5));
System.out.println(Math.round(2.5));
System.out.println(Math.round(-2.5));
/*
2.0
-3.0
3.0
-2.0
3
-2
*/

Random r = new Random();

/*
public boolean nextBoolean();
随机数范围为:false、true
*/
boolean b1 = r.nextBoolean();
System.out.println(b1);
/*
false
*/

/*
public int nextInt();
随机数范围为: int的区间
*/
int i1 = r.nextInt();
System.out.println(i1);
/*
-1098866320
*/

/*
public long nextLong();
随机数范围为: long的区间
*/
long l1 = r.nextLong();
System.out.println(l1);
/*
8115353135541459577
*/

/*
public int nextInt(int n);
随机数范围为:[0,n)
*/
int i2 = r.nextInt(100);
System.out.println(i2);
/*
71
*/

/*
public float nextFloat();
随机数范围为:[0,1)
*/
float f1 = r.nextFloat();
System.out.println(f1);
/*
0.42610747
*/

/*
public double nextDouble();
随机数范围为:[0,1)
*/
double d2 = r.nextDouble();
System.out.println(d2);
/*
0.28172834985842776
*/

/*
public void setSeed(long seed)
设置在种子数的基础上进行一定的变换产生随机数。
相同种子数的Random对象,相同次数生成的随机数字是完全相同的。即第1次生成的随机数相同

,第2次生成的随机数也相同,......,第n次生成的随机数也相同。
*/
Date date = new Date();
long time = date.getTime();
Random r2 = new Random();
Random r3 = new Random();
r2.setSeed(time);
r3.setSeed(time);
int i21 = r2.nextInt(100);
int i22 = r2.nextInt(100);
int i23 = r2.nextInt(100);
int i31 = r3.nextInt(100);
int i32 = r3.nextInt(100);
int i33 = r3.nextInt(100);
System.out.println(i21 + " " + i22 + " " + i23);
System.out.println(i31 + " " + i32 + " " + i33);
/*
96 57 5
96 57 5
*/

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: