0

I am trying to write a code that shows the last digit (in a set of 3) is the same. I could not understand why I got false for each set so, I decided to test -20%10 and I got -0 meanwhile 20%10 gives me the expected 0. What is this -0 about?

function last_digit( x, y, z){

if(x % 10 == y % 10 == z % 10 ){
return true;

}else {
return false;

}

}
console.log(last_digit(20, 30, 400));
console.log(last_digit(-20, 30, 400));
console.log(last_digit(20, -30, 400));
console.log(last_digit(20, 30, -400));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
appletree
  • 57
  • 6
  • 1
    Possible duplicate of [Are +0 and -0 the same?](https://stackoverflow.com/questions/7223359/are-0-and-0-the-same) – Evan Trimboli Oct 09 '17 at 13:55
  • Your comparison is equal to `x % 10 == (y % 10 == z % 10)`. I.e. you compare `x % 10` with a boolean result. What you want is something like `x % 10 == y % 10 && y % 10 == z % 10`. – Some programmer dude Oct 09 '17 at 13:58
  • @appletree, please use `===` for (pretty much) all comparisons. why? because `true == 1` check `last_digit(5, 15, 21)` with your code. – Thomas Oct 09 '17 at 15:31
  • I think in playing around with the code to try to understand why I was getting -0, my if clause got botched. I didnt realize I posted it this way, and I am grateful for the help. Cheers all! – appletree Oct 10 '17 at 05:00

2 Answers2

1

You need to compare the values pair wise with a logical AND &&, because the first comparison returns a boolean value and the next is comparing this value with the rest of the following expression.

function last_digit(x, y, z) {
    return x % 10 == y % 10 && x % 10 == z % 10;
}

console.log(last_digit(20, 30, 400));
console.log(last_digit(-20, 30, 400));
console.log(last_digit(20, -30, 400));
console.log(last_digit(20, 30, -400));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Do it this way,

function last_digit(x, y, z) {

  if ((x % 10) == (y % 10) && (y % 10) == (z % 10)) {
    return true;

  } else {
    return false;

  }

}
console.log(last_digit(20, 30, 400));
console.log(last_digit(-20, 30, 400));
console.log(last_digit(20, -30, 400));
console.log(last_digit(20, 30, -400));
Shane G
  • 3,129
  • 10
  • 43
  • 85