[英]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
-10
的unsigned int
等效值。
This occurs because the size()
function of std::vector
returns a size_t
, which is unsigned. 发生这种情况是因为
std::vector
的size()
函数返回一个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_t
, int
被提升为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.