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));

4
  • 1
    Possible duplicate of Are +0 and -0 the same? Commented Oct 9, 2017 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. Commented Oct 9, 2017 at 13:58
  • @appletree, please use === for (pretty much) all comparisons. why? because true == 1 check last_digit(5, 15, 21) with your code. Commented Oct 9, 2017 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! Commented Oct 10, 2017 at 5:00

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

1 Comment

No wonder, I was not getting true for all of them. Thanks Nina
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.