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 trialbaderbouta
7,804 PointsThe guessed answer is never good, forever in a loop?
I've pulled half of my hair out, why is this code not working? Thanks in advance.
var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
var correctGuess = false;
function getRandomNumber( upper ) {
var num = Math.floor(Math.random() * upper) + 1;
return num;
}
do {
guess = prompt('give us a random number between 1 and 10');
guessCount += 1;
if (parseInt(guess) === randomNumber) {
correctGuess = true;
}
} while ( ! correctGuess )
document.write('<p> Congrats! You guessed it right, it took you ' + guessCount + 'attempts </p>');
3 Answers
Aakash Srivastava
5,415 PointsHey baderbouta , I copied your code and it works for me...
It may took many attempts to guess the right one , i guessed correctly in 66 attempts.
Best way would be to check the code would be by lowering the value from 10 to 3 or 4 and you will take lesser attempts to guess it.
Hope it helped :)
baderbouta
7,804 PointsThanks a lot!
Aakash Srivastava
5,415 PointsYou are most welcome :)
Christopher Evans
9,896 PointsI had this same issue and I can't understand why it takes so many attempts.
I changed upper to 3, so it could only be one of three numbers, and yet it still took me hundreds of attempts to guess the right number. How is this possible? I get that it's technically random each time, but that's incredibly statistically unlikely.