I try to multiply three number but I get a strange result. Why I get so different results?
unsigned int a = 7;
unsigned int b = 8;
double d1 = -2 * a * b;
double d2 = -2 * (double) a * (double) b;
double d3 = -2 * ( a * b );
// outputs:
// d1 = 4294967184.000000
// d2 = -112.000000
// d3 = 4294967184.000000
In your first example, the number
-2is converted to unsigned int. The multiplication results in -112, which when represented as unsigned is 2^32 – 112 = 4294967184. Then this result is finally converted todoublefor the assignment.In the second example, all math is done on doubles, leading to the correct result. You will get the same result if you did:
as
-2.0is adoubleliteral.