小编Geo*_*ang的帖子

Why doesn't a negative number modulo a vector size give a negative number?

#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;
}
Run Code Online (Sandbox Code Playgroud)

The above code prints:

-4
7
5
-4
Run Code Online (Sandbox Code Playgroud)

Can someone please explain why i % v.size() prints 5 instead of -4? I'm guessing it has something to do …

c++ integer-promotion modulus

23
推荐指数
3
解决办法
1146
查看次数

标签 统计

c++ ×1

integer-promotion ×1

modulus ×1