简体   繁体   English

意外的数学分部输出 - C ++

[英]Unexpected Mathematical Division Output - C++

I have this segment of testing code (there is quite a lot of other material; however, it is extremely dense and likely irrelevant to this question), which has been producing some inexplicable output. 我有这段测试代码(有很多其他材料;但是,它非常密集,可能与这个问题无关),这已经产生了一些莫名其妙的输出。 When compiled, this block: 编译时,此块:

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;

produces the output: 产生输出:

10 
30 
2 
2 
10 
2147483638

'team1' and 'team2' are both of type vector<player> (without backslash) and the 'player' struct appears as follows: 'team1'和'team2'都是vector<player> (没有反斜杠),'player'结构如下所示:

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

team1.size() and team2.size() are unsigned ( size_t ) - change your code to: 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;

(team1[m].rating - team2[n].rating) is equal to -20 . (team1[m].rating - team2[n].rating)等于-20 This expression result is being promoted to unsigned int according to rules of mixed expressions and divided by team1.size() , yielding 2147483638 which is the unsigned int equivalent for signed int -10 . 根据混合表达式的规则将此表达式结果提升为unsigned int ,并除以team1.size() ,得到2147483638 ,它是signed int -10unsigned int等效值。

This occurs because the size() function of std::vector returns a size_t , which is unsigned. 发生这种情况是因为std::vectorsize()函数返回一个unsigned的size_t When dividing an int (such as the rating) by a size_t , the int is promoted to an unsigned int . int (例如rating)除以size_tint被提升为unsigned int

Converting a negative number to an unsigned value will cause that value to underflow, becoming larger than the maximum positive value which can be represented by the original signed type. 将负数转换为无符号值将导致该值下溢,变得大于可由原始签名类型表示的最大正值。

In order to prevent this, you need to explicitly state that the size() arguments should be converted to int before the division. 为了防止这种情况,您需要明确声明在分割之前应将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;

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

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