0

How would I make it where every time it generates a random number it adds it on to a variable called Num my code is below.

function Generate() {
    var Num;
    var RanN = Math.floor((Math.random()*10)+1);
    for (var i=0;i<4;i++) {
        Num += RanN;
    }
}
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
CDW
  • 33
  • 5

4 Answers4

0

If you're trying to generate a random number i amount of times and add it to a pre-existing number, you'll want something like this:

function Generate(startNum, iterations) {
   for (var i=0; i<iterations; i++) {
      startNum +=  Math.floor((Math.random()*10)+1);
   }
   return startNum;
}

And you would use it like this (if you want to add ten randomly generated numbers):

var num = 0;
num = Generate(num, 10);

Here's a fiddle.

DeeDee
  • 2,641
  • 2
  • 17
  • 21
0

Here is what I think the OP want:

function Generate(Num) {
    for (var i=0;i<4;i++) {
        Num += Math.floor((Math.random()*10)+1);
    }
    return Num;
}
Sebastien
  • 1,308
  • 2
  • 15
  • 39
0

The answers are slightly different in structure to your function. If you want to fix what you have (seeing that you have moved the random function into the loop), just change var Num; to var Num=0;, which will fix the NaN error (because you can't add a number to something that is not defined, because it is Not a Number)

Chris M
  • 209
  • 1
  • 3
  • You're correct in your suggestion, but he's not going to get anything back the way his function is currently written. It's going to add the same randomly-generated number four times and then *poof*. @Sebastien and I have both given him something he can actually use and build on. – DeeDee Mar 04 '14 at 23:34
  • @DeeDee, fair point, and your answers are great, I just thought that it hadn't been made explicit that the thing crashing it was the above. CDW had moved the random() line following Sebastien's comment, so I wanted to help CDW to fix their own code. – Chris M Mar 06 '14 at 08:09
0

If what you want is a random int you could use:

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomInt(1111, 9999));

You can find more info here.

Community
  • 1
  • 1
a--m
  • 4,716
  • 1
  • 39
  • 59