Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模与无符号整数_C++_Unsigned_Modulus - Fatal编程技术网

C++ 模与无符号整数

C++ 模与无符号整数,c++,unsigned,modulus,C++,Unsigned,Modulus,我发现以下行为令人惊讶: int a = -2; int b = 5; uint c = 5; std::cout << a%b << '\n'; std::cout << a%c << '\n'; Output: -2 4 inta=-2; int b=5; uint c=5; std::cout假设uint是一个无符号类型,不小于int,在表达式a%c的计算中,a被转换为uint,它的值为-2+std::numeric\u limits::

我发现以下行为令人惊讶:

int a = -2;
int b = 5;
uint c = 5;
std::cout << a%b << '\n';
std::cout << a%c << '\n';

Output:
-2
4
inta=-2;
int b=5;
uint c=5;

std::cout假设
uint
是一个
无符号
类型,不小于
int
,在表达式
a%c
的计算中,
a
被转换为
uint
,它的值为
-2+std::numeric\u limits::max()+1

对于32位
uint
,该数字为4294967294,模5为4

对于16位
uint
,该数字是65534,模5也是4


参考资料:

谢谢。好的,没有比较,但是
%
触发相同的转换。你能指出一个有记录的地方吗?@stafusa:我添加了一个几乎代表标准的引用。啊,好吧-我搜索了“模数”,但没有找到:以下算术运算符的参数进行隐式转换,以获得通用实数类型,即执行计算的类型:二进制算术*,/,%,+,-“@stafusa:没错!请随意将所有这些拼凑在一起,并回答您自己的问题。我会向上投票。注意a%b也可以是3。这是实现定义的负数上的weather%有一个正或负的结果。@GoswinvonBrederlow不是从C++11开始的。@GoswinvonBrederlow请看链接没有提到天气/必须向0或向下取整。引用的C++11部分仅表示
(a/b)*b+a%b等于a
。至少在过去,a/b在不同的CPU上会有不同的取整方式,这是标准所允许的。%然后更改以保持所述的相等性。@GoswinvonBrederlow当它说“对于整数操作数,/运算符产生代数商,任何小数部分都被丢弃”时,我理解它意味着截断完成了,因此“舍入”为零。