赞
踩
使用Math.random()产生给定范围内的随机数:
*Math.random()本身可以产生[0,1)内的任意随机浮点数,利用Math.random()进行四则运算
*则可以产生给定范围内的整数或浮点数
*详解在代码注释里
- package com.atcording.java;
-
- public class RandomTest {
- public static void main(String[] args){
- /*
- * 使用Math.random()产生给定范围内的随机数:
- * Math.random()本身可以产生[0,1)内的任意随机浮点数,利用Math.random()进行四则运算
- * 则可以产生给定范围内的整数或浮点数
- */
- double num1,num2;
- num1=Math.random()*90;//任意产生[0.0,90.0)的浮点数
- num2=Math.random()*90+10;//任意产生[10.0,100.0)的浮点数
- int num3=(int)(Math.random()*90+10);//任意产生[10,99]的整数
- //(int)可以把后面的(Math.random()*90+10)这个浮点型数强制转化为整型
- //因为Math.random()*90+10产生的数范围为[10.0,100.0),但像99.10这种小数强
- //制转化为整型取整后为99,所以整数范围为[10,99]
- int num4=(int)(Math.random()*90+1+10);//任意产生[10,100]的整数
- //公式:[a,b]:(int)(Math.random()*(b-a+1)+a)
- System.out.println(num1);
- System.out.println(num2);
- System.out.println(num3);
- System.out.println(num4);
- }
-
- }

输出结果如下:
如果有用就点个赞吧!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。