简体   繁体   English

C++:奇怪的除法输出

[英]C++: strange division output

I have the following codes:我有以下代码:

    int x = arr[arr.size() -1] - arr[0];
    int n = arr.size();
    int dx = x/n;
    int dy = (arr[arr.size() -1] - arr[0])/arr.size();
    std::cout << dx << "  " << dy << std::endl;

when my arr = [15, 13, 12] , I got dx = -1 , but dy = 1431655764 ( arr is vector<int> )当我的arr = [15, 13, 12] ,我得到dx = -1 ,但dy = 1431655764arr is vector<int>

Why dx and dy are different?为什么dxdy不同? Thanks!谢谢!

Why dx and dy are different?为什么dxdy不同?

For dy , note that the return type of std::vector::size is std::vector::size_type , which is an unsigned integer type.对于dy ,请注意std::vector::size的返回类型是std::vector::size_type ,它是一个无符号整数类型。 Then the result of (arr[arr.size() -1] - arr[0])/arr.size() is unsigned too.然后(arr[arr.size() -1] - arr[0])/arr.size()也是无符号的。 The result is overflowed , then assigned to dy with type int .结果溢出,然后分配给int类型的dy

Unsigned integer arithmetic is always performed modulo 2 n where n is the number of bits in that particular integer.无符号整数算术总是以2 n执行,其中 n 是该特定整数中的位数。 Eg for unsigned int , adding one to UINT_MAX gives ​0 ​, and subtracting one from ​0​ gives UINT_MAX .例如,用于unsigned int ,加入一种至UINT_MAX给出​0 ,并从一个减去​0​给出UINT_MAX

For dx , arr.size() is assigned to n (whose type is int ) firstly, then gets calculated as x/n , whose result is int too.对于dxarr.size()首先分配给n (其类型为int ),然后计算为x/n ,其结果也是int Then the result is assigned to dx and anything is fine.然后将结果分配给dx一切正常。

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

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