本文介绍了负数的模运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 C 程序中,我尝试了以下操作(只是为了检查行为)

In a C program I was trying the below operations (Just to check the behavior)

 x = 5 % (-3);
 y = (-5) % (3);
 z = (-5) % (-3);

printf("%d ,%d ,%d", x, y, z);

它在 gcc 中给了我 (2, -2 , -2) 的输出.我每次都期待一个积极的结果.模数可以是负数吗?任何人都可以解释这种行为吗?

It gave me output as (2, -2 , -2) in gcc. I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?

推荐答案

C99 要求 a/b 可表示时:

C99 requires that when a/b is representable:

(a/b) * b + a%b 应等于 a

这在逻辑上是有道理的.对吧?

让我们看看这会导致什么:

Let's see what this leads to:

示例 A.5/(-3)-1

=> (-1) * (-3) + 5%(-3) = 5

只有当 5%(-3) 为 2 时才会发生这种情况.

This can only happen if 5%(-3) is 2.

示例 B.(-5)/3-1

=> (-1) * 3 + (-5)%3 = -5

仅当 (-5)%3-2

这篇关于负数的模运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 20:31