gpt4 book ai didi

C++:除以 vector.size() 给出奇怪的结果

转载 作者:太空狗 更新时间:2023-10-29 23:33:26 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
int divided by unsigned int causing rollover

您好,我正在做以下事情:

struct coord{
int col;

};


int main(int argc, char* argv[]) {

coord c;
c.col = 0;

std::vector<coord> v;

for(int i = 0; i < 5; i++){
v.push_back(coord());
}

c.col += -13;


cout << " c.col is " << c.col << endl;
cout << " v size is " << v.size() << endl;

c.col /= v.size();


cout << c.col << endl;

}

我得到以下输出:

 c.col is -13
v size is 5
858993456

但是,如果我将分隔线更改为 c.col/= ((int)v.size()); 我会得到预期的输出:

 c.col is -13
v size is 5
-2

这是为什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com