Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGloria Gasbarra
4,487 PointsMy code is really different, but it works. What's wrong?
var first = prompt("Which is the first number?");
var last = prompt("Which is the last number?");
var random = (parseInt (Math.random() * (first, last)) + 1 );
document.write(random + " is a number between " + first + " and " + last);
2 Answers
A X
12,842 PointsHi Gloria, You're right your code works as long as you "play fairly"...like I set out to break your code, and I put in the first number of 0 and the last number of 0 and got this result:
Random Number Generator 1 is a number between 0 and 0 (which is False)
I also tried 0 and 1:
Random Number Generator 1 is a number between 0 and 1 (which is False)
I also tried strings, and floats:
Random Number Generator NaN is a number between one and two
Random Number Generator 1 is a number between .1 and .3
I also tried negative numbers:
Random Number Generator 0 is a number between -1 and -2 (which is False)
So you could look at this result a few ways, like oh geez, I have ways of breaking the program! Or you could say, that's ok I like the way the program runs..... but mainly there's nothing "wrong" with what you did if you don't want to account for my ways of breaking the program. The Math.floor in the video is attempting to prevent breaking the program from some of the breaks I tried from your version.
Abhijit Das
5,022 Pointsif I am not wrong isn't should be like as the video code: var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumber + 1) + bottomNumber); instead the +1 at last place?
Gloria Gasbarra
4,487 PointsGloria Gasbarra
4,487 PointsThanks @nekilof, you're great! I didn't try. Then your text I tried with the video's code...
var input1 = prompt("Please type a starting number");
var bottomNumber = parseInt(input1);
var input2 = prompt("Please type a number");
var topNumber = parseInt(input2);
var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumber + 1) + 1);
var message = "<p>" + randomNumber + " is a number between 1 and " + topNumber + " .</p>";
document.write(message);
I tried 0 and 1: Random Number Generator 2 is a number between 1 and 1 .
I tried -1 and -2: Random Number Generator 1 is a number between 1 and -2 .
I tried 20 and 30: Random Number Generator 4 is a number between 1 and 30 .
(The counting starts always from the number 1)
I don't know... What do you think?