简体   繁体   English

为什么javascript返回-0

[英]why does javascript return -0

I am trying to write a code that shows the last digit (in a set of 3) is the same. 我正在尝试编写一个显示最后一位数字(一组为3)的代码。 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? 我不明白为什么每个集都会出错,所以我决定测试-20%10,而我得到-0,同时20%10给了我期望的0。这是什么意思-0?

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

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. 您需要将两个值与逻辑AND &&进行成对比较,因为第一个比较将返回一个布尔值,而第二个将此值与以下表达式的其余部分进行比较。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM