C++:奇怪的除法输出

C++: strange division output

我有以下代码:

    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;

当我的 arr = [15, 13, 12] 时,我得到了 dx = -1,但是 dy = 1431655764 (arr is vector<int>)

为什么 dxdy 不同?谢谢!

Why dx and dy are different?

对于dy,注意std::vector::size is std::vector::size_type, which is an unsigned integer type. Then the result of (arr[arr.size() -1] - arr[0])/arr.size() is unsigned too. The result is overflowed的return类型,然后赋值给dy类型int

Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer. E.g. for unsigned int, adding one to UINT_MAX gives ​0​, and subtracting one from ​0​ gives UINT_MAX.

对于dx,先将arr.size()赋值给n(其类型为int),然后计算为x/n,结果为int 也是。然后把结果赋值给dx就可以了