简体   繁体   中英

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:

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:

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 . 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 .

This occurs because the size() function of std::vector returns a size_t , which is unsigned. When dividing an int (such as the rating) by a size_t , the int is promoted to an 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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