Home > Backend Development > C++ > How Does the Modulus Operator Handle Negative Numbers in C/C /Obj-C?

How Does the Modulus Operator Handle Negative Numbers in C/C /Obj-C?

Patricia Arquette
Release: 2024-11-08 03:56:01
Original
446 people have browsed it

How Does the Modulus Operator Handle Negative Numbers in C/C  /Obj-C?

Modulus Operator Handling Negative Numbers in C/C /Obj-C

Unlike in mathematics, the modulus operator (%) in C-derived languages exhibits inconsistent behavior when applied to negative numbers. This discrepancy arises from the ambiguity surrounding the sign of the remainder.

Implementation-Defined Behavior

According to the C 03 standard, the sign of the remainder when both operands are negative is implementation-defined. This means that different compilers and platforms may produce varying results for operations such as (-1) % 8 and fmodf(-1, 8).

Reliable Expression

Regardless of the implementation, the following expression holds true:

(a / b) * b + (a % b) == a
Copy after login

This expression states that the dividend (a) can be reconstructed from the quotient (a / b) and the remainder (a % b).

Solution

One approach to ensure consistent behavior for negative operands is to calculate the remainder as follows:

<code class="cpp">int mod(int a, int b) {
  if (b < 0)
    return -mod(-a, -b);
  int ret = a % b;
  if (ret < 0)
    ret += b;
  return ret;
}</code>
Copy after login

This function handles negative operands by negating both operands in case b is negative. The remainder is calculated as a % b. If the remainder is negative, it is adjusted by adding the absolute value of b. This ensures that the result is a non-negative remainder that satisfies the abovementioned reliable expression.

In this way, mod(-1, 8) would return 7, and mod(13, -8) would return -3, adhering to the expected mathematical behavior.

The above is the detailed content of How Does the Modulus Operator Handle Negative Numbers in C/C /Obj-C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template