为什么对向量大小取模的负数不能给出负数? [英] Why doesn't a negative number modulo a vector size give a negative number?

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

问题描述

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  vector<int> v = {1, 2, 3, 4, 5, 6, 7};
  int i = -4;

  cout << i << endl;
  cout << v.size() << endl;
  cout << i % v.size() << endl;
  cout << -4 % 7 << endl;
}

上面的代码打印:

-4
7
5
-4

有人可以解释为什么i % v.size()打印5而不是-4吗?我猜想它与vector.size()有关,但是不确定潜在的原因是什么.提前致谢.

Can someone please explain why i % v.size() prints 5 instead of -4? I'm guessing it has something to do with vector.size(), but unsure what the underlying reasoning is. Thanks in advance.

推荐答案

在执行除法之前,%的操作数经过通常的算术转换以使其成为通用类型.如果操作数是intsize_t,则int将转换为size_t.

The operands of % undergo the usual arithmetic conversions to bring them to a common type, before the division is performed. If the operands were int and size_t, then the int is converted to size_t.

如果size_t是32位,则-4会变成4294967292,然后表达式的结果是4294957292 % 7,实际上是0.

If size_t is 32-bit then -4 would become 4294967292 and then the result of the expression is 4294957292 % 7 which is actually 0.

如果size_t是64位,则-4将变为18,446,744,073,709,551,612,并且此% 7的结果是您看到的5.

If size_t is 64-bit then -4 would become 18,446,744,073,709,551,612 and the result of this % 7 is 5 which you saw.

因此实际上我们可以从此输出中得知您的系统具有64位size_t.

So actually we can tell from this output that your system has 64-bit size_t.

这篇关于为什么对向量大小取模的负数不能给出负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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