1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Getting a random number between two variables in JS?

Discussion in 'JavaScript' started by Mnsoldier5, Feb 24, 2019.

  1. #1
    I am working on an assignment and I am having difficulty writing up the function to get a random number between two variables.

    Basically what I want is the script to prompt you for the first number followed by the second then give me a random number in between those two.

    How do I get a random whole number in between two user inputted variables?

    Now I will show you the code:
    <!DOCTYPE html>
    <html>
    <body>
    <script>
    var age = prompt ("How old are you?");
    var videogames = prompt ("How many hours of video games have you played last month?");
    function getRndInteger(age, videogames) {
      return Math.floor(Math.random() * (videogames - age)) + age;
    }
    document.write (getRndInteger(age,videogames));
    </script>
    
    </body>
    </html>
    Code (JavaScript):

     
    Mnsoldier5, Feb 24, 2019 IP
  2. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,151
    Likes Received:
    1,656
    Best Answers:
    29
    Trophy Points:
    475
    #2
    Not sure if this is what you want: https://jsfiddle.net/h0xftysu/

    
    <html>
    <body>
    <script>
    var age = prompt ("How old are you?");
    var videogames = prompt ("How many hours of video games have you played last month?");
    function getRndInteger(age, videogames) {
      return Math.floor(Math.random() * (videogames + age));
    }
    document.write (getRndInteger(age,videogames));
    </script>
    
    </body>
    </html>
    
    Code (markup):
     
    qwikad.com, Feb 24, 2019 IP
  3. Mnsoldier5

    Mnsoldier5 Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    That doesn't appear to be working I tested age as 1 and video games as 10 and it outputted 56, no idea how.
    What did work for me is

    function getRndInteger(...args) {
      const [low, high] = [Math.min(...args), Math.max(...args)];
      return Math.floor(Math.random() * (high - low)) + low;
    }
    var age = prompt ("How old are you?");
    var videogames = prompt ("How many hours of video games have you played last month?");
    
    document.write getRndInteger(age,videogames));
    Code (JavaScript):
     
    Mnsoldier5, Feb 24, 2019 IP