Computer Science Canada Random Number Question |
Author: | rto [ Tue Dec 16, 2008 8:53 am ] | ||
Post subject: | Random Number Question | ||
Assignment : Write a program that uses a for loop and an array to store 100 random nitegers in the range of 0 to 1000. using a second for loop, calculate the average of the random numbers. have the program do this 10 times and print out the average each time. What i have :
Im not too worried about the loss of precision error because that is easy enough to fix, the random number error im getting is annoying me though ![]() thanks |
Author: | jernst [ Tue Dec 16, 2008 10:12 am ] | ||
Post subject: | Re: Random Number Question | ||
rto @ Tue Dec 16, 2008 8:53 am wrote:
It looks like you are missing a bracket here. There is no match for the closing bracket at the end. |
Author: | rto [ Tue Dec 16, 2008 11:12 am ] |
Post subject: | RE:Random Number Question |
(int) (Math.random()*1000)+1; thats the aswer to my question, the +1 has to be OUTSIDE the brackets ![]() |
Author: | DemonWasp [ Tue Dec 16, 2008 11:40 am ] | ||
Post subject: | RE:Random Number Question | ||
Math.random takes 0 arguments. It returns a double in the range 0 - 0.99999..., what you're looking for is something like the following:
First, Math.random generates a number in its specified range 0 - 0.999...; then we "expand" that range to 0 - 999.999 by multiplying by 1000, we shift it by adding one - 1 - 1000.999...) - and then limit it by casting to integer: 1 - 1000. A note on includes: it is generally considered good practice to only ever include what you really need (however tempting it may be to say import *). This is because you can sometimes use the imported file list to determine which of several identically-named classes is being used in the code. A modern editor designed for Java should have the capacity to do this automatically; in Eclipse it's Ctrl+Shift+O. Edit: tried to use proper range notation, with square brackets. It didn't work. |