Edamame
Edamame

Reputation: 25366

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>)

Why dx and dy are different? Thanks!

Upvotes: 1

Views: 62

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

Why dx and dy are different?

For dy, note that the return type of 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, then assigned to dy with type 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.

For dx, arr.size() is assigned to n (whose type is int) firstly, then gets calculated as x/n, whose result is int too. Then the result is assigned to dx and anything is fine.

Upvotes: 6

Related Questions