Reputation: 39
I need to generate a random number between 8 and 32. then multiply to the power of 2. then repeat it in a loop 10 times. I can't figure how to generate the number within a range this is what i have so far.
function btnGenerate_onclick()
{
// assign textbox elements to variables for easier access
var outputTextbox = document.getElementById("txtOutput");
for(var i = 0; i < 10; i++)
{
System.out.println(Math.pow(2, Math.floor(Math.random() * 32 + 1); ));
}
outputTextbox.value = ;
}
Upvotes: 0
Views: 433
Reputation: 4839
In plain english:
Math.random returns a number between 0 and 1.
http://www.w3schools.com/jsref/jsref_random.asp
Multiply that by the range between the numbers number2-number1
to get a number that is between 0
and greatest range-1
. We can call it range
.
Add the lower bound number number1
to get a number that is between number1
and number2
Here is the program in plunker http://plnkr.co/edit/gXSxTl03BFTFDMVFd0YC?p=preview
var random = Math.random();
var number1 = 5.0;
var number2 = 12;
var range = number2-number1;
var rangedRandom = range*random;
var rangedRandomPlusLeast = number1+rangedRandom;
var rangedRandomPlusLeastAsInteger = Math.round(rangedRandomPlusLeast);
Upvotes: 1
Reputation: 3816
Math.random()
gives a number between 0.0 and 1.0. If you multiply it by 32, you get a number between 0.0 and 32.0. If you want something between 8 and 32, you should do Math.random() * 24 + 8
. That will give you something between 8.0 and 32.0.
Upvotes: 1
Reputation: 5110
Following code generates random number between 50 and 100 (Both inclusive).
final int MAX = 100;
final int MIN = 50;
.
.
.
Random r = new Random();
// nextInt is normally exclusive of the MAX value,
// so add 1 to make it inclusive
int randomNumber = r.nextInt((MAX-MIN) + 1) + MIN;
Upvotes: 2