JavaScript 如何使用模除运算符得到负结果
在JavaScript中,%(模除)运算符给出两个数字相除所得到的余数。在模除和余数运算符之间有一个区别。当在正数上计算余数或%(模除)时,它们的行为是相似的,但当使用负数时,它们的行为是不同的。
JavaScript中的%(模除)运算符的行为类似于余数运算,它给出余数,并且由于数字是负数,因此余数也是负数。
让我们理解并比较模除和余数运算结果的清晰度。
模除运算符的示例:
For Positive Numbers:
Input: a = 21, b = 4
Output: 1*Explanation:
modulo = 21 % 4
modulo = 21 - 4 * 5
modulo = 21 - 20 = 1
Other Explanation:**
The number 21 can be written in terms of 4 as
21 = 5 * 4 + 1
So, here '1' is the result.
For Negative Numbers:
Input: a = -23, b = 4
Output: 1
Explanation:
modulo = -23 % 4
modulo = -23 + 4 * 6
modulo = -23 + 24 = 1
Other Explanation:
The number -23 can be written in terms of 4 as
-23 = (-6) * 4 + 1
So, here '1' is the result.
示例:
Remainder operator uses the formula:
Remainder = a - (a / b) * b
Note: Result of (a / b) is first converted into Integer Value.
For Positive Numbers:
Input: a = 21, b = 4
Output: 1
Explanation:
Remainder = 21 - (21 / 4) * 4
Remainder = 21 - 5 * 4
Remainder = 21 - 20 = 1
For Negative Numbers:
Input: a = -23, b = 4
Output: -3
Explanation:
Remainder = -23 -( -23 / 4) * 4
Remainder = -23 -(-5) * 4
Remainder = -23 + 20 = -3
因此,从上面的比较可以明确得知余数运算和模运算是不同的。JavaScript的%(模)运算符实际上就是余数运算符,这就是为什么它在负数上给出负结果的原因。
Number.prototype : 原型构造函数允许向JavaScript数字添加新属性和方法,以使所有数字都具有此属性,并可以默认访问该方法。因此,我们将使用 Number.prototype 来创建一个返回两个数字的模运算结果的函数。
语法:
Number.prototype.mod = function(a) {
// Calculate
return this % a;
}
以下程序示例展示了JavaScript中的%(取模)运算符:
示例1: 这个示例使用取模运算符(%)进行操作。
<script>
// JavaScript code to perform modulo (%)
// operation on positive numbers
// mod() function
Number.prototype.mod = function(a) {
// Calculate
return this % a;
}
// Driver code
var x = 21;
var b = 4;
// Call mod() function
var result = x.mod(b);
// Print result
console.log("The outcome is: " + result);
</script>
输出:
The outcome is: 1
示例2:
<script>
// JavaScript code to perform modulo (%)
// operation on negative numbers
// Use mod() function
Number.prototype.mod = function(a) {
// Calculate
return this % a;
}
// Driver code
var x = -21;
var b = 4;
// Call mod()
var result = x.mod(b);
// Print result
console.log("The outcome is: " + result);
</script>
输出:
The outcome is: -1
因此,清楚为什么JavaScript的百分比(%)给出负结果。
更改JavaScript的百分比(%)以使其像模运算符: 为了执行模运算符(%)而不是计算余数,我们将使用以下公式。假设数字为a和b,然后计算 mod = a % b
语法:
Number.prototype.mod = function(b) {
// Calculate
return ((this % b) + b) % b;
}
在上面的公式中,我们使用模运算的模性质计算出余数的模值 (a + b) mod c = (a mod c + b mod c) mod c 。下面的程序演示了上述方法。
示例: 这个示例解释了上述方法。
<script>
// JavaScript implementation of above approach
// Use mod() function
Number.prototype.mod = function(b) {
// Calculate
return ((this % b) + b) % b;
}
// Driver code
var x = -21;
var b = 4;
// Call mod() function
var result = x.mod(b);
// Print result
console.log("The outcome is: " + result);
x = -33;
b = 5;
// Call mod() function
result = x.mod(b);
// Print result
console.log("The outcome is: " + result);
</script>
输出:
The outcome is: 3
The outcome is: 2