Reputation: 1284
I'm not a C++ developer, but today I've found a C++ code and try to understand it. So I've stacked on this piece of code:
int m = 2, n = 3, i = 1;
double mid = (double)m / n * i;
int d = (int)mid + 1;
printf("%d %d\n", mid, d);
The result which is going to be printed to the console is: 1431655765 1071994197. It seems to be related with the casting of variable m to double, but I have no idea how it is happening. I need someone to help me understand it. Thanks in advance!
Upvotes: 4
Views: 31523
Reputation: 1
A simpler way to solve it would be
double m_Doubled;
m_Doubled = static_cast(m);
Upvotes: 0
Reputation: 2165
Changing the printf to
printf("%f %i\n", mid, d);
will actually print what you expect i.e., 0.666667 1
Upvotes: 1
Reputation: 70929
You should print a double(mid
) with the %lf
format specifier in printf
.
Upvotes: 5