I had one question about my assignment. It is necessary to make it so that the program itself guesses the number entered by the user. Here is my solution, but there is one problem: the program guesses that number, but sometimes repeats the values ​​of min or max. Something like "Your number is greater than or equivalent to 13?" - For example, I answer yes (that is, the number is not equivalent, but more :), and it may again ask "Is your number greater or equivalent to 13?", and after that continues to work normally. Please tell me what is wrong?

function guess_programm() { var number; var min = 0; var max = 30; var random_number = Math.floor(min + (max-min+1)*Math.random()); number = prompt('Hi, let\'s play the game! Enter your number(from 0 to 30) and I will try to guess it :)', 'I close my eyes, so you can write -o-'); while (max != min || min != max) { var answer = prompt('OK, your number bigger then or it is equally to - ' + random_number, 'equally/yes/no'); if (answer == 'equally') { alert('Yeeh, I wiin ^^'); break; } else if (answer == 'yes') { min = random_number; } else if (answer == 'no') { max = random_number; } random_number = Math.floor(min + (max-min+1)*Math.random()); } alert('Your number is - ' + number); } 
  • max != min || min != max max != min || min != max is a JS feature that == is non-transitive and should be written like this? - pavel

1 answer 1

Here is the construction

 Math.floor(min + (max-min+1)*Math.random()) 

you get a random number from minimum to maximum - including it may be the minimum or maximum itself. And one of them is just that number which was at the last stage.

In general, in such tasks it is better to use not a random number from the interval, but its middle.

  • min = random_number; there probably need one more. - pavel
  • @pavel and if random_number would be the maximum? - Alexey Shimansky
  • one
    @ Alexey Shimansky, we were told that it was more than his plans, since we entered this thread. Otherwise, it is possible on a pair [1,2] for example to take the middle (1) and the eternal cycle. - pavel