模量随负数 [英] Modulus with a negative number

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

问题描述

可能显示的文件:结果
  <一href=\"http://stackoverflow.com/questions/43775/modulus-operation-with-negatives-values-weird-thing\">Modulus与底片值操作 - 奇怪的事情?结果
  负数的mod正在融化我的脑袋!

我试图做 25%-9 只是为了好玩,我得到的答案是-2(这是在谷歌),当我在C $ C $这样做三我有7人能解释我为什么两个不同的答案?

I tried doing 25 % -9 just for fun and the answer I got was -2 (this was on Google) and when I did this in C code I got 7. Can someone explain me why two different answers?

推荐答案

在C89 / 90,无论是结果还是允许的。从除法和余数得到的结果必须适合在一起,使(A / B)* B + A%B == A

In C89/90, either result was allowed. The results you got from division and remainder were required to "fit" together so that (a/b)*b + a%b == a.

与C99,整数除法对于负的输入开始时需要向零截断。从除法和余数的结果之间的关系仍然需要,但。这意味着,(实际上)从余运算结果总是具有相同的符号作为左操作数,因此25%-9必须产率7,不-2

Starting with C99, integer division with a negative input is required to truncate toward zero. The relationship between the results from division and remainder is still required though. This means that (in effect) the result from the remainder operation always has the same sign as the left operand, so 25 % -9 must yield 7, not -2.

有关它的价值,C ++大致遵循相同的路径,短短几年落后C. C ++ 98/03具有相同的规则为C89 / 90,所以你的投入,其余可以是阴性或阳性(但仍需要与来自划分结果)装配在一起。与C ++ 11开始,它需要相同的行为,C99,所以25% - 9 == 7

For what it's worth, C++ followed roughly the same path, just a few years behind C. C++98/03 has the same rules as C89/90, so for your inputs the remainder could be either negative or positive (but still needs to fit together with the result from division). Starting with C++11, it requires the same behavior as C99, so 25 % - 9 == 7.

其他一些语言(例如,Python)的要求,从剩余的结果具有相同的符号作为右操作数来代替。

Some other languages (e.g., Python) require that the result from remainder have the same sign as the right operand instead.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆