2

我有这段测试代码(还有很多其他材料;但是,它非常密集,可能与这个问题无关),它一直在产生一些莫名其妙的输出。编译时,此块:

cout << team1[m].rating << endl;
cout << team2[n].rating << endl;
cout << team1.size() << endl;
cout << team2.size() << endl;
cout << (team2[n].rating - team1[m].rating) / team2.size() << endl;
cout << (team1[m].rating - team2[n].rating) / team1.size() << endl;

产生输出:

10 
30 
2 
2 
10 
2147483638

'team1' 和 'team2' 都是类型vector<player>(没有反斜杠),并且 'player' 结构如下所示:

struct player {
string name;
int rating;
player(string Name, int Rating) :
    name(Name), rating(Rating) {}
};
4

3 回答 3

9

team1.size()并且team2.size()是无符号 ( size_t) - 将您的代码更改为:

cout << (team2[n].rating - team1[m].rating) / static_cast<int>(team2.size()) << endl;
cout << (team1[m].rating - team2[n].rating) / static_cast<int>(team1.size()) << endl;
于 2012-11-21T08:21:54.553 回答
5

(team1[m].rating - team2[n].rating)等于-20。这个表达式结果正在unsigned int根据混合表达式的规则被提升并除以team1.size(),产生2147483638相当于unsigned intsigned int -10

于 2012-11-21T08:26:28.407 回答
4

发生这种情况是因为size()函数std::vector返回 a size_t,它是无符号的。当将 an int(例如评级)除以 asize_t时,将int提升为 a unsigned int

将负数转换为无符号值将导致该值下溢,变得大于原始有符号类型可以表示的最大正值。

为了防止这种情况,您需要明确声明 size() 参数应int在除法之前转换为。

cout << (team2[n].rating - team1[m].rating) / static_cast<int>(team2.size()) << endl;
cout << (team1[m].rating - team2[n].rating) / static_cast<int>(team1.size()) << endl;
于 2012-11-21T08:32:43.707 回答