ARTICLE AD BOX
In this line:
double my_double_value = -my_size_t_value*cash;According to operator precedence first -my_size_t_value is calculated, and according to the C++ rules done in "unsigned mode" because size_t is unsigned.
So an expression that negates a small size_t will produce a large positive value - for example: negating a size_t with value 2 produces the value std::numeric_limits<size_t>::max()-1 which, for a 32-bit size_t, is 4294967294 and for 64-bit size_t is 18446744073709551614
(the latter matches your case according to the final output of 1.84467e+22).
Only then the result is converted to double for multiplying by cash.
So it is equivalent to:
double my_double_value = (-my_size_t_value)*cash;If you change it to:
double my_double_value = -(my_size_t_value*cash);You will get the expected result because now first the multiplication will be done, and for that my_size_t_value will be converted to double.
See live demo.
Using int (which is signed) instead of size_t (unsigned) gives you the expected result because now the unary negation does what you expect.
35.9k18 gold badges79 silver badges112 bronze badges
6 Comments
Explore related questions
See similar questions with these tags.

