为什么0.86%1不为零而是0.86,因为0.86 / 1给出余数为0?

时间:2017-01-07 06:55:08

标签: javascript math modulo

如果模数(%)与正数的“余数(r)”相同,那么为什么“0.86%1”结果为“0.86”而不是“0”,因为“0.86 / 1 = 0.86”,其余为= 0。

我已经看到了其他问题,但没有一个问题解决了1个条件下的模型。我能够理解这一点的唯一方法是认为0.86小于1,因此不能除以1,因此返回0.86作为余数。

2 个答案:

答案 0 :(得分:5)

你说

  

“0.86 / 1 = 0.86”,余数= 0。

嗯,只有在5/2 = 2.5且余数为0的意义上,很清楚这有什么不对,对吗?

当我们谈论余数时,商必须是整数。它不能是2.5或0.86。如果你尽可能多地从除数中除去除数的倍数,剩下的就是余数。对于5/2,我们有

5-2 = 3
3-2 = 1
2>1, so we can't subtract any more, and the remainder is 1

对于0.86 / 1,我们有

1>0.86, so we can't subtract any copies of 1 from 0.86, and the remainder is 0.86

答案 1 :(得分:4)

我猜你没有正确理解数学。

 0.86
-----  =  0 Quotient & 0.86 Remainder
  1

这是因为1足够大,1在0.86中变为0,剩余0.86。

0.86 % 1 // This gives remainder, not the quotient.

所以你在看什么,是对的。如果您想查看整个结果的数量,那么您需要执行parseInt()

parseInt(0.86/1, 10); // This gives you 0!

更好的解释

function divide(up, down) {
  if (down == 0)
    return false;
  var res = up / down;
  var rem = up % down;
  console.log("Result (Quotient): " + parseInt(res, 10));
  console.log("Remainder:         " + rem);
}

console.log(divide(0.86, 1));
console.log(divide(7, 2))