简体   繁体   中英

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!

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 2 n where n is the number of bits in that particular integer. Eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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