Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Anwar H
Anwar H
921 Points

Are we looking to generate random numbers between the upper and lower numbers and including the upper and lower number?

I might be wrong but my understanding is we're looking to generate numbers "between" two values (an upper and lower number). If I designate an upper and lower number, say (100, 95), I was assuming I'd get 96,97,98, and 99. But the code also gives me 95 and 100 as well. How, can we modify the code to generate only the numbers between two values?

Antony .
Antony .
2,812 Points

post code pls

Anwar H
Anwar H
921 Points

May bad. Here is the code:

function getRandomNumber( lower, upper ) {

return Math.floor(Math.random() * (upper - lower + 1)) + lower; }

console.log( getRandomNumber( 'nine', 24 ) );

console.log ( getRandomNumber( 95, 100 ) );

console.log( getRandomNumber( 200, 'five hundred' ) );

console.log( getRandomNumber( 1000, 20000 ) );

console.log( getRandomNumber( 50, 100 ) );

Antony .
Antony .
2,812 Points

If you want some insight on how this line of code works, i suggest looking at this answer by Jason Anello https://teamtreehouse.com/community/mathfloor-mathrandom-max-min-1-min-explanation

function getRandomNumber(lower, upper) {
    return Math.floor(Math.random() * (upper - lower - 1)) + lower + 1;
}
console.log(getRandomNumber(95, 100));
Antony .
Antony .
2,812 Points

Just for better reading, use the Markdown Cheatsheet on learning how to embed your code https://teamtreehouse.com/community/howto-guide-markdown-within-posts

2 Answers

Steven Parker
Steven Parker
216,012 Points

You are correct, in this case "between" means including the highest and lowest values. Typically with computers (as opposed to mathematics) you will see this word used in the inclusive sense. Another example is the SQL language for databases which has a BETWEEN keyword that is inclusive.

But you can modify the formula to give you an exclusive "between":

    return Math.floor(Math.random() * (upper - lower - 1)) + lower + 1;
Antony .
Antony .
2,812 Points

I said the same thing, but always happy to see you helping around steven! :D

Steven Parker
Steven Parker
216,012 Points

I guess I got distracted for a while as I was composing that!

Anwar H
Anwar H
921 Points

Thanks guys. really appreciate your quick responses!