整数除以JavaScript中的余数?

整数除以JavaScript中的余数?

在JavaScript中,我如何获得:

  1. 给定整数进入另一个整数的整数倍?

  2. 剩下的?


波斯汪
浏览 460回答 3
3回答

米琪卡哇伊

对于某些数字y和一些除数,x将quotient(quotient)和remainder(remainder)计算为:var quotient = Math.floor(y/x);var remainder = y % x;

扬帆大鱼

我不是按位运算符的专家,但这是获得整数的另一种方法:var num = ~~(a / b);这也适用于负数,而Math.floor()在错误的方向上。这似乎也是正确的:var num = (a / b) >> 0;

倚天杖

我在Firefox上进行了一些速度测试。-100/3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// -33.33..., 0.3663 millisecMath.floor(-100/3) // -34,&nbsp; &nbsp; &nbsp; &nbsp;0.5016 millisec~~(-100/3)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// -33,&nbsp; &nbsp; &nbsp; &nbsp;0.3619 millisec(-100/3>>0)&nbsp; &nbsp; &nbsp; &nbsp; // -33,&nbsp; &nbsp; &nbsp; &nbsp;0.3632 millisec(-100/3|0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// -33,&nbsp; &nbsp; &nbsp; &nbsp;0.3856 millisec(-100-(-100%3))/3&nbsp; // -33,&nbsp; &nbsp; &nbsp; &nbsp;0.3591 millisec/* a=-100, b=3 */a/b&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // -33.33..., 0.4863 millisecMath.floor(a/b)&nbsp; &nbsp; // -34,&nbsp; &nbsp; &nbsp; &nbsp;0.6019 millisec~~(a/b)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // -33,&nbsp; &nbsp; &nbsp; &nbsp;0.5148 millisec(a/b>>0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// -33,&nbsp; &nbsp; &nbsp; &nbsp;0.5048 millisec(a/b|0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // -33,&nbsp; &nbsp; &nbsp; &nbsp;0.5078 millisec(a-(a%b))/b&nbsp; &nbsp; &nbsp; &nbsp; // -33,&nbsp; &nbsp; &nbsp; &nbsp;0.6649 millisec以上是基于每个1000万次试验。结论:使用(a/b>>0)(或(~~(a/b))或(a/b|0))可以使效率提高约20%。也请记住,他们都是不一致Math.floor的时候a/b<0 && a%b!=0。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript