• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

random numbers

 
simon kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
what could be the ans for the following qs..
Which of the following will output a random with values only from 1 to 10?
1) System.out.println(Math.round(Math.random()* 10));
2) System.out.println(Math.round(Math.random() % 10));
3) System.out.println(Math.random() *10);
4) None of the above
i feel it should be (1) and (3)..
plz verify it..
simon
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simon, why don't you compile and run the code and see how it works... What does Math.random do? What does Math.round do? You have to ask yourself those questions...
in the third case, a double is returned which is probably not what we want (between 1 and 10 not 1.0 and 10.0)...
HIH
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by simon kumar:
Hi,
what could be the ans for the following qs..
Which of the following will output a random with values only from 1 to 10?
1) System.out.println(Math.round(Math.random()* 10));
2) System.out.println(Math.round(Math.random() % 10));
3) System.out.println(Math.random() *10);
4) None of the above
i feel it should be (1) and (3)..
plz verify it..
simon

Actually, I'm not so sure if any of them will work. Valentin's right - you should try this code out for yourself and see what it does - that's whay I just did.
I was right - none of them work. The answer is, which one's will give a value between 1 and 10. (You should also know if this is exclusive or inclusive.) However, the closest ones are the first and third. Unfortunately, both of them can give values that are less than 1 because Math.random() can return a value from 0.0 to 1.0. Take a look - I'm sure you'll find this to be the case.
If you really want to get a value between 1 and 10 (I'll do inclusive), you'll need to do something like this:

Try and figure it out and, if you can't let me know and I'll explain further.
Corey
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<nodding head> yup, I agree with Corey. None of the statements given as answers will produce the requested output. So the answer to the original test question is "none of the above."
Actually, you don't need the call to Math.round().
You can just do
(int)(Math.random()*9+1)
[ February 12, 2002: Message edited by: Rob Ross ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic