Home >Backend Development >C++ >Why Does the Modulo Operator Produce Negative Results with Negative Numbers?

Why Does the Modulo Operator Produce Negative Results with Negative Numbers?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 09:55:25202browse

Why Does the Modulo Operator Produce Negative Results with Negative Numbers?

Modulo Operator Results in Negative Values: A Mathematical Explanation

The modulo operator %, when applied to negative numbers, can produce different results depending on the implementation. This can be puzzling, but understanding the mathematical definition of the modulo operator can shed light on this behavior.

According to ISO14882:2011(e) 5.6-4, the modulo operator returns the remainder of the division of the first expression by the second. If the second operand is zero, the behavior is undefined. For integral operands, the quotient is the algebraic quotient with any fractional part discarded.

To illustrate this, consider the following examples:

std::cout << (-7 % 3) << std::endl; // -1
std::cout << (7 % -3) << std::endl; // 1

(-7 % 3) = -1

  • -7 divided by 3 yields an algebraic quotient of -2.
  • -2 multiplied by 3 gives -6.
  • The remainder of -7 divided by 3 is therefore -1.

(7 % -3) = 1

  • 7 divided by -3 yields an algebraic quotient of -2.
  • -2 multiplied by -3 gives 6.
  • The remainder of 7 divided by -3 is therefore 1.

Note that in both cases, the algebraic quotient is the same (-2). The difference in the remainder results from the implementation-defined sign of the remainder when both operands are of different signs.

The above is the detailed content of Why Does the Modulo Operator Produce Negative Results with Negative Numbers?. 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