Math.random()詳解


 

Math.random()是令系統隨機選取大於等於 0.0 且小於 1.0 的偽隨機 double 值,是Java語言常用代碼。例如:double a=Math.random()*(3-1)+1,設置一個隨機1到3的變量。

 

代碼

Math.random():產生一個[0,1)之間的隨機數。
返回指定范圍的隨機數(m-n之間)的公式  [1]  :
1
2
Math.random()*(n-m)+m;
改正公式:Math.random()*(n+ 1 -m)+m
例:
生成一個6位的隨機字符串:
1
2
3
4
5
6
7
8
9
10
11
public  static  void  main(String[]args){
String result= "" ;
for (inti= 0 ;i< 6 ;i++){
//生成97-122的int型的整型
int  intValue=( int )(Math.random()* 26 + 97 );
//將intValue強制轉化成char類型后接到result后面
result=result+( char )intValue;
}
//輸出字符串
System.out.println(result);
}

使用方法

例:用Math類的random()方法產生一個字符,若該字符是一個大寫英文字母,則輸入 "Yes!",否則輸出“NO”。
random()方法產生的 隨機數在0.0和1.0之間,乘以128后,其值在0.0和128.0之間,將它轉換為 char類型后,用if來判斷是否在'A' 和'Z'之間。程序如下:
1
2
3
4
5
6
7
8
9
10
classIsUpper{
publicstaticvoidmain(String[]args){
charch;
ch=( char )(Math.random()* 128 );
if (ch>= 'A' &&ch<= 'Z' )
System.out.println( "Yes!" );
else
System.out.println( "No!" );
}
}
JavaScript Math.random() 函數
Math.random() -- 返回0和1之間的偽隨機數 可能為0,但總是小於1,[0,1)
1
document.write(Math.random());
返回隨機數
1
document.write(Math.random()*( 20 - 10 + 1 )+ 10 );
返回10-20的隨機數
1
document.write(Math.random()*(n+ 1 -m)+m);
返回指定范圍的隨機數(m-n之間)的公式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM