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

问题描述

在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);

给了我为输出(2,-2,-2)在gcc中。我每次期待一个肯定的结果。模数可以是负的?任何人都可以解释这种现象?

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 重新presentable

C99 requires that when a/b is representable:

(A / B)* B + A%B 应等于 A

(a/b) * b + a%b shall equal a

这是有道理的,在逻辑上。右?

让我们看看这会导致:

例A. 5 /( - 3) 1

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

=> 5%( - 3) 2

=> 5%(-3) should be 2

示例B ( - 5)/ 3 1

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

=> ( - 5)%3 -2

=> (-5)%3 should be -2

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

07-02 08:06