简体   繁体   English

当其中一个操作数为负值c ++时的模数运算

[英]modulus operation when one of the operand is negative value c++

I have a vector<int> table and an int index=-833099133 我有一个vector<int> table和一个int index=-833099133

When I write 当我写作

cout<<table.size()<<endl;
cout<< index%table.size()<<endl;

It gives me : 它给了我:

83
  81

however If I write 但如果我写

cout<<index%83<<endl;

output turns out: 输出结果:

-79

Is there anyone to help me why it occurs ? 有没有人帮我解释它为什么会发生? thanks in advance 提前致谢

table.size() is of type std::vector<int>::size_type , which is an unsigned type (usually std::size_t ), but the literal 83 is an int which is signed. table.size()的类型为std::vector<int>::size_type ,它是一个无符号类型(通常是std::size_t ),但是文字83是一个有符号的int

When performing an operation on a signed and an unsigned integer, the signed one is implicitly converted ("promoted") to an unsigned value. 对有符号和无符号整数执行操作时,已签名的整数将被隐式转换(“提升”)为无符号值。 That results in a non-negative number which is the original value modulo some power of two (which power is used depends on the width of the unsigned type). 这导致非负数,这是原始值模数为2的幂(使用的功率取决于无符号类型的宽度)。 In your case, size_t was 32 bits long, so 在你的情况下, size_t是32位长,所以

-833099133 == 3461868163 (mod 2 ^ 32)

and of course, 3461868163 % 83 is 81, whereas -833099133 % 83 is -79. 当然, 3461868163 % 83是81,而-833099133 % 83是-79。 ( -833099133 mod 83 would be +4, but in C++, the % is not the modulo, but the remainder operator.) -833099133 mod 83将是+4,但在C ++中, %不是模数,而是余数运算符。)

Indeed, if you run the following program on a system where std::size_t is 32 bits long: 实际上,如果在std::size_t为32位长的系统上运行以下程序:

#include <iostream>

int main()
{
    int idx = -833099133;
    int signed83 = 83;
    std::size_t unsigned83 = 83;

    std::cout << idx % signed83 << std::endl;
    std::cout << idx % unsigned83 << std::endl;

    return 0;
}

you will get the same results. 你会得到相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM