public class RandInt{
public static void main(String args[]){
int a=0;
a=(int) (Math.random()*10); //why do i use (int) in Math.random?
System.out.println(a);
}
}
Saturday, April 4, 2009
[Java] 建立整數亂數
Subscribe to:
Post Comments (Atom)
java, c/c++, actionscript, perl, php, mysql, flex, flash......
public class RandInt{
public static void main(String args[]){
int a=0;
a=(int) (Math.random()*10); //why do i use (int) in Math.random?
System.out.println(a);
}
}
3 意見:
According to Java SE 6 API, the random() function will return a double value with the standard distribution [0, 1]. You need to do a type casting while generating a integer random number.
因為randon()它是屬於double 的 value,所以需要*10才會是整數.
[問題]那麼我為何要用(int)(Math.randon()*10);
,為何不直接用double i =Math.randon()*10;,這兩者的意思不是都是亂數嗎?跑出來的結果也是一樣的.
No difference between these two methods?
Did you ever test it on your program?
WITHOUT type casting, we can not consider a double value as an integer just by multiplying it by any number. For instance, 0.275 * 10 = 2.75. 2.75 is still in floating point.
Post a Comment