Home >Backend Development >C++ >Usage of % in c++
The modulo operator (%) calculates the remainder of the division of two numbers. The rules are as follows: Divide positive numbers: the remainder is non-negative and less than the divisor. Division of negative numbers: the remainder is negative and its absolute value is less than the absolute value of the divisor. Divide a positive number by a negative number: the remainder is negative and its absolute value is less than the absolute value of the divisor. Divide a negative number by a positive number: the remainder is positive and less than the divisor.
The modulo operator (%) in C
The modulo operator (%) is used to calculate The remainder obtained after dividing two numbers. It is a binary operator, which means it requires two operands.
Grammar
<code class="cpp">result = operand1 % operand2;</code>
Operation rules
Example
<code class="cpp">int a = 10 % 3; // 结果为 1 int b = -10 % 3; // 结果为 -1 int c = 10 % -3; // 结果为 1 int d = -10 % -3; // 结果为 -1</code>
Note
The modulo operator can be used to solve various programming problems, such as:
Other uses
The modulo operator can also be used for bit operations , used to get specific bits of a binary number:
<code class="cpp">int mask = 1 << 3; // 创建一个掩码,表示二进制数的第 4 位 int result = number & mask; // 对 number 进行位与运算,提取第 4 位</code>
In this way, we can check or set specific bits of a binary number.
The above is the detailed content of Usage of % in c++. For more information, please follow other related articles on the PHP Chinese website!