2014-01-25 16 views
0

我有一个vector<int> table和一个int index=-833099133模运算时的操作数中的一个是负的值C++

当我写

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

它给我:

83 
    81 
然而

如果我写

cout<<index%83<<endl; 

输出证明:

-79 

是否有任何人来帮助我,为什么它会发生?由于事先

+3

'table.size()'是无符号的,'83'是一个'int',它被签名...然后整数提升,一些黑魔法,并且你得到了你的结果。 – 2014-01-25 20:03:09

+0

@ H2CO3感谢您的回复,您可以将它写为答案我想接受它 – TheGost

+0

@TheGhost完成。 – 2014-01-25 20:19:07

回答

2

table.size()std::vector<int>::size_type类型,这是一个无符号类型(通常std::size_t),但字面83是被签署int

对有符号和无符号整数执行操作时,有符号整数会被隐式转换(“提升”)为无符号值。这会导致一个非负数,这个数是原始值的某个幂模(取决于无符号类型的宽度)。在你的情况,size_t为32位长,所以

-833099133 == 3461868163 (mod 2^32) 

当然和,3461868163 % 83是81,而-833099133 % 83是-79。 (-833099133 mod 83将是4,但在C++中,%不是模,但其余运算符。)

事实上,如果一个系统,其中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; 
} 

你会得到同样的结果。

相关问题