一、原理
Math.random()获取的是[0,1)的随机数;然后根据需要变更;
二、实例
1、如何获取一个0-100的随机数?
Math.random() * 100
2.如何获取一个2-98的随机数?
public class random1 {
public static void main(String[] args) {
double a=Math.random();
double b=Math.random()*100;
/*获取2-98的随机数*/
double c=Math.random()*96+2;
//这里的思路是,2-98范围等于(0-96)+2;然后提取公因式,变成(0-1)*96+2;前面的0-1可以用Math.random()来替换
//System.out.println(a);
//System.out.println(b);
System.out.println(c);
}
}

本文介绍了如何使用Java的Math.random()方法生成特定范围内的随机数,并通过实例演示了如何生成0到100以及2到98之间的随机整数。

677

被折叠的 条评论
为什么被折叠?



