随机数Math.random()的常见用法

语法:Math.random()        

返回值:一个浮点型伪随机数字,在0(包括 0)和1(不包括)之间。它不能被用户选择或重置。不可重复使用,想要重复使用随机数的值,只能声明一个变量来保存。

public class Test {
	public static void main(String[] args) {
		//随机数Math.random();
		System.out.println(Math.random());	    //随机生成一个0-1中间的浮点数	
	}
}

如何获取在某一个范围之内的随机数

double number=Math.random()*(max-min)+min;

public class Test {
	public static void main(String[] args) {
		/*控制随机数的获取范围
		 * 获取一个999-10000之间的随机数
		 */
		System.out.println((Math.random()*(10000-999)+999));		
	}
}

如何获取在某一个范围之内的随机整数

int number=(int)(Math.random()*(max-min)+min);

注:Math.random()  获取的值为一个随机浮点数,如果想要获取一个随机整数就需要强转,注意
——强转会丢失精度

public class Test {
	public static void main(String[] args) {
		/*控制随机数的获取范围
		 * 获取一个999-10000之间的随机整数
		 */
		System.out.println((int)(Math.random()*(10000-999)+999));		
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值