Home >Backend Development >C++ >How Does the Modulo Operator Handle Negative Numbers?

How Does the Modulo Operator Handle Negative Numbers?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 03:10:13574browse

How Does the Modulo Operator Handle Negative Numbers?

Understanding the Modulo Operator's Behavior with Negative Values

The modulo operator is known to yield different results when used with negative operands. To delve into this, let's consider the following operations:

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

Rationale According to the ISO Standard

According to ISO14882:2011(e) 5.6-4, the modulo operator (%) yields the remainder from the division of the first expression by the second. However, for integral operands like in our case, the division operator (/) performs integer division, discarding any fractional part.

Mathematical Breakdown

Let's break down the calculations for clarity:

  • (-7 / 3) results in -2, and (-2 * 3) is -6. Therefore, -7 % 3 yields -1, since (-6 - (-7)) = -1.
  • (7 / -3) results in -2, and (-2 * -3) is 6. Thus, 7 % -3 yields 1, as (6 - 7) = 1.

Implementation-Defined Behavior

It's important to note that when both operands are negative, the sign of the remainder is implementation-defined. However, as of ISO14882:2011(e), the behavior is no longer explicitly stated as in its predecessor, ISO14882:2003(e).

The above is the detailed content of How Does the Modulo Operator Handle 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