Home >Backend Development >C++ >Usage of % in c++

Usage of % in c++

下次还敢
下次还敢Original
2024-04-26 18:51:151089browse

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.

Usage of % in c++

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

  • Division of two positive numbers: The result is a non-negative remainder, less than the divisor.
  • Dividing two negative numbers: The result is a negative remainder, and the absolute value is less than the absolute value of the divisor.
  • Dividing a positive number by a negative number: The result is a negative remainder whose absolute value is less than the absolute value of the divisor.
  • Dividing a negative number by a positive number: The result is a positive remainder that is less than the divisor.
  • Cannot perform modulo operation on floating point numbers.

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

  • If the divisor is 0, then take Modulo arithmetic can cause runtime errors.
  • The modulo operator has lower precedence than arithmetic operators.
  • The modulo operator can be used to solve various programming problems, such as:

    • Count the number of loops
    • Determine whether a number can be modified by another number Divide a number
    • Generate random numbers

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Usage of ~ in c++Next article:Usage of ~ in c++