%(mod)具有混合签名 [英] % (mod) with mixed signedness

查看:97
本文介绍了%(mod)具有混合签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用c ++中的环形2D网格(即,它缠绕在侧面),并编写了一个明显的邻居/相对点函数:

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.

我以为我理解%运算符,甚至还记得检查否定结果.尽管如此,我还是开始尝试它. 'width'是一个无符号的值160,所以我尝试了:

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;

...,我很震惊地看到95的结果.

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

到底发生了什么?

推荐答案

事实证明,我的程序未将无符号的160u强制转换为int.
而是将-1转换为无符号,变成4294967295,实际上,如果将其乘以160,则得到95.

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.

为什么c ++这样做超出了我的范围,但我发布了此内容,以便其他人可以从我的经验中学到东西. 底线:使用%时请勿混合有符号和无符号整数!

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 %!

这篇关于%(mod)具有混合签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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