Results 1 to 2 of 2
Thread: Math.random generating 0
- 03-25-2011, 07:56 AM #1
Math.random generating 0
Hi all,
I have create the following code in the hope of producing four random numbers from 1 to 6.
Sometimes a '0' is returned, but I can't figure out why! :o
Java Code:for (int i = 1; i <= 4; i++ ) { int num = (int)(Math.random() * (1 + 6)); System.out.print(num); }
Can someone please help me?
Many thanks!
- 03-25-2011, 08:17 AM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 7
Math.random returns a number from 0.0 to less than 1.0, which means there is more than a ten percent chance that a number smaller than 0.142 (approximately a 14.2% chance, obviously) and that number times 7 (why you do 1+6 there I don't know) is still less than 1.0 and casting a number smaller than 1 to int will produce 0.
Edit: Use the Random class and "nextInt(6) + 1"
Similar Threads
-
Generating random numbers
By chinedum in forum New To JavaReplies: 9Last Post: 09-21-2011, 05:03 AM -
generating double random number between 0 and 1
By sara12345 in forum New To JavaReplies: 6Last Post: 04-17-2010, 08:04 PM -
generating random number between 0 and 1
By sara12345 in forum New To JavaReplies: 1Last Post: 04-17-2010, 07:54 PM -
Generating a random number
By oridov in forum New To JavaReplies: 2Last Post: 11-29-2008, 05:12 PM -
generating random numbers in a 5x5 array.
By acidacid in forum New To JavaReplies: 3Last Post: 08-14-2007, 03:44 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks