返回指定范围的随机数(m-n之间)的公式
document.write(Math.random()*(n+
1
-m)+m);
例如:
返回10-20的随机数
document.write(Math.random()*(
20
-
10
+
1
)+
10
);
一个字符,若该字符是一个大写英文字母,则输入 "Yes!",否则输出“NO”。
Math.random() -- 返回0和1之间的伪随机数 可能为0,但总是小于1,[0,1)
random()方法产生的随机数在0.0和1.0之间,乘以128后,其值在0.0和128.0之间,将它转换为char类型后,用if来判断是否在'A' 和'Z'之间。
class{
public static void main(String[]args){
char ch;
ch=(
char
)(Math.random()*
128
);
if
(ch>=
'A'
&&ch<=
'Z'
)
System.out.println(
"Yes!"
);
else
System.out.println(
"No!"
);
}
}
获取1995年这一年中的一个随机数:
public
static
void
main(String[] args) {
long
second =
1000
;
long
minute =
60
*second;
long
hour = minute *
60
;
long
day = hour*
24
;
long
year = day *
365
;
long
year1995Start = (
1995
-
1970
) * year;
long
leapDay = (
1995
-
1970
)/
4
*day;
//每隔4年有一个润日
year1995Start+=leapDay;
long
eightHour = hour*
8
;
//8个小时的毫秒数,因为从0毫秒对应的是1970.1.1 08:00:00
year1995Start-=eightHour;
Date dStart =
new
Date(year1995Start);
System.out.println(
"1995年第一天:"
+dStart);
long
year1995End = year1995Start + year -
1
;
Date dEnd =
new
Date(year1995End);
System.out.println(
"1995年最后一天:"
+dEnd);
long
randomTime = (
long
) (Math.random()*(year-
1
) + year1995Start);
Date dRandom =
new
Date(randomTime);
System.out.println(
"1995年这一年中的一个随机时间:"
+ dRandom);