std::cbrt
returns a floating point type (float, double, etc.) but you are converting it to an int
. Such conversions truncate rather than round e.g. 0.9999 becomes 0. Although it may seem logical that the cube root of 2197 is an integer, due to the fact that floating point types are stored in binary, it is not always possible to perfectly represent a decimal number, and such inaccuracies are likely to propagate during the calculations that std::cbrt
performs. If for example, std::cbrt(2197) == 12.99999
(my compiler doesn't support it so I can't check the real value), then by converting it to an int
you are truncating the value to 12.
To correct your code, round the result of std::cbrt(i)
before converting it to an int
. See this question for an idea of how to do that.