负数模运算 [英] Modulo operation with negative numbers
本文介绍了负数模运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 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
这篇关于负数模运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文