% (mod) with mixed signedness

血红的双手。 提交于 2019-12-11 11:55:35

问题


I was working with a toroidal 2D grid in c++ (ie. it wraps around at the sides), and wrote an obvious neighbor / relative-point function:

point neighbor(point p0, int dx, int dy)
{
    point p=p0;
    p.x += dx;
    p.y += dy;
    p.x %= width; if(p.x<0) p.x += width;
    p.y %= height; if(p.y<0) p.y += height;
    return p;
}

I was totally clueless why my program wasn't working, since the implementation of this function seemed trivial.

I thought I understood the % operator, I even remembered to check for negative results. Still, I started experimenting with it; 'width' was an unsigned with a value of 160, so I tried:

cout << (-1) % 160u;

... and I was shocked to see a result of 95.

What the heck is going on?


回答1:


As it turned out, my program didn't cast the unsigned 160u to int.
Rather, -1 is converted to unsigned becoming 4294967295, which in fact gives 95 when modded by 160.

Why c++ does so is beyond me, but I'm posting this so others may learn from my experience. Bottom line: Do not mix signed and unsigned integers when using %!



来源:https://stackoverflow.com/questions/12877988/mod-with-mixed-signedness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!