Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {}
};
like image 998
Michael Hang Avatar asked Jan 31 '26 08:01

Michael Hang


2 Answers

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;
like image 181
Paul R Avatar answered Feb 01 '26 22:02

Paul R


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

like image 32
SomeWittyUsername Avatar answered Feb 02 '26 00:02

SomeWittyUsername



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!