如何code模(%)运算符在C / C ++ /的OBJ-C处理负数 [英] How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

查看:143
本文介绍了如何code模(%)运算符在C / C ++ /的OBJ-C处理负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个宠物C-衍生语言讨厌(作为一个数学家)是

One of my pet hates of C-derived languages (as a mathematician) is that

(-1) % 8 // comes out as -1, and not 7

fmodf(-1,8) // fails similarly

什么是最好的解决方案?

What's the best solution?

C ++允许模板和操作符重载的可能性,但是这两个都是我的浑水。例子感激地接受。

C++ allows the possibility of templates and operator overloading, but both of these are murky waters for me. examples gratefully received.

推荐答案

所有我想指出,你甚至不能依靠事实先说( - 1)%8 == - 1 。你可以依靠的唯一的事情就是(X / Y)* Y +(X%Y)== X 。然而,剩下的是否是负的实现定义的。

First of all I'd like to note that you cannot even rely on the fact that (-1) % 8 == -1. the only thing you can rely on is that (x / y) * y + ( x % y) == x. However whether or not the remainder is negative is implementation-defined.

现在这里为什么用模板?对于整型和长过载会怎么做。

Now why use templates here? An overload for ints and longs would do.

int mod (int a, int b)
{
   int ret = a % b;
   if(ret < 0)
     ret+=b;
   return ret;
}

和现在你可以这样调用它MOD(-1,8),它会显示为7。

and now you can call it like mod(-1,8) and it will appear to be 7.

编辑:我发现了一个bug在我的code。如果b为负值,那么将无法工作。所以我觉得这是更好的:

I found a bug in my code. It won't work if b is negative. So I think this is better:

int mod (int a, int b)
{
   if(b < 0) //you can check for b == 0 separately and do what you want
     return mod(a, -b);   
   int ret = a % b;
   if(ret < 0)
     ret+=b;
   return ret;
}

参考:C ++ 03第5.6段第4条:

Reference: C++03 paragraph 5.6 clause 4:

二元/运营商产生的商,和二元运算符%收益率从第二个第一八佰伴pression的余数。如果/或%第二个操作数为零的行为是不确定的;否则(A / B)* B + A%b等于一。如果两个操作数都是非负则剩余部分非负; 如果不是,剩余的标志是实现定义

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

这篇关于如何code模(%)运算符在C / C ++ /的OBJ-C处理负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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