Programme doesn't work

Hey guys, a newbie here! :slight_smile:

i’m trying to create a programme that given a random number should check if one of the two guesses nailed it. In case none of the options are correct the programme should tell which one got closer to the random number.

So far I’ve created the following:

var playerOne = 5;
var playerTwo = 4;
var casual = Math.floor(Math.random() * (100-1) + 1);
var wrongOne = (playerOne != casual);
var wrongTwo = (playerTwo != casual);
var a = (casual - playerOne);
var b = (casual - playerTwo);
var closer0ne = (a < b);
var closerTwo = (a > b);

console.log("Casual number is: " + casual);
console.log("Player one choose the number: " + playerOne);
console.log("Player two choose the number: " + playerTwo);

if (playerOne === casual) {
  console.log("Well done player one! you nailed it!");
if (playerTwo === casual) {
  console.log("Well done player two! you nailed it!");
else if (wrongOne) { 
  if (closer0ne) {
    console.log("No one guess it right, but player one is the one got closer!");
else if (wrongTwo) {
  if (closerTwo){
  console.log("No one guess it right, but player two is the one got closer!");

As said i’m learning, I’m ok with the random number, I’m ok in checking if one of the answer is correct but i can’t process the right code to check which numbers is the closer. Any suggestion please?

Thanks a lot!

P.S. I probably should have use less variables and trying to make it shorter but this way of breaking it down I thought it’d have been easier to sorted out.

To check who is closest to casual you’ll need two more variables to subtract both guesses from casual.

Turn both results into a positive number (you can use Math.abs for that)

The smalles number is the one closest to casual and wins. You should also think of what you want to do when the result is that both players guessed an equal distance from casual

Thanks Silvith,

all clear now!

1 Like