nenito
nenito

Reputation: 1284

C++ casting int to double

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

Answers (3)

Emeche Cash
Emeche Cash

Reputation: 1

A simpler way to solve it would be

double m_Doubled;
m_Doubled = static_cast(m);

Upvotes: 0

PoP
PoP

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

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

You should print a double(mid) with the %lf format specifier in printf.

Upvotes: 5

Related Questions