gpt4 book ai didi

javascript - Javascript如何计算模数?

转载 作者:搜寻专家 更新时间:2023-11-01 05:11:45 26 4
gpt4 key购买 nike

我一直在用 Javascript 进行一些测试,我将展示它们(从控制台粘贴):

-1 % 4
-1
-4 % 4
-0
-8 % 4
-0
-6 % 4
-2
-6 % -4
-2
6 % -4
2

-1 % 4 确实是 -1,但是,我真的不明白为什么 Javascript 不产生 3,这同样正确,但更规范。

什么是-0?我知道 -4/4 = -1,这是一个整数,但我不确定 -0 是什么。

我对Javascript的模数计算感到困惑。

我的测试是出于一个有点不愉快的意外,我一直在处理一个画廊,并且我有一个事件图片的索引。有两个按钮,用于下一个和上一个按钮。上一张图片的下一张图片是第一张图片,第一张图片的上一张图片是最后一张图片。我一直在将索引更改为:

currentImageIndex = (currentImageIndex + 1) % images.length;

当用户点击下一步按钮时。当用户点击上一个按钮时,我一直在尝试使用以下代码:

currentImageIndex = (currentImageIndex - 1) % images.length;

令我惊讶的是后者并没有很好地工作,因为之前的图像没有显示,并且由于在 currentImageIndex 索引的数组中使用了无效索引而抛出了错误。我有 console.log-ed 值并且看到它是 -1!好的,我已经解决了这个问题:

currentImageIndex = (currentImageIndex + images.length - 1) % images.length

虽然不是很痛苦,但我仍然不明白计算结果背后的逻辑。那么,有没有人知道 Javascript 的模计算是如何工作的,因为我真的很困惑,我看到 -0 作为 -4 % 4 的结果是这个月的笑话。

最佳答案

好问题!

在我看来,ECMA 令人困惑,而且很容易忘记模运算符的工作原理(我确实做到了)。来自 ECMA-262 §11.5.3有声明说:

The result of a floating-point remainder operation as computed by the % operator…

推断出余数运算。它继续提供一种算法:

…where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. r is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode.

将其应用于 -1 % 4 的情况,则:

n = -1
d = 4
trueMathematicalQuotient = -1/4 = -0.25

因此 q 必须是负数,因为 n/d 是负数。 d (4) 可以乘以量级小于或等于 -0.25 并且给出的结果小于或等于 n 的最大负整数(-1) 是 -0(注意 -1 的 magnitude 大于 -0.25)。

做到这一点的简单方法是将 q chop 为一个整数:

q = -0 // -0.25 truncated

将数字代入方程式:

r = -1 - (4 * 0)
r = -1 - 0
r = -1

它可以放在一个函数中:

function remainderMod(n, d) {
var q = parseInt(n / d); // truncates to lower magnitude
return n - (d * q);
}

或缩写为:

function remainderMod(n, d) {
return n - (d * (n/d | 0));
}

关于javascript - Javascript如何计算模数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com