Click to See Complete Forum and Search --> : Type conversion.
arunkumar_gona
July 1st, 2002, 01:26 PM
--------------------------------------------------------------------------
unsigned int x = 100;
unsigned int y = 200;
float f;
f = (float)x-(float)y; // ok result -100.000
f = (float)(x-y); // Not ok , result 4.29497e+009
--------------------------------------------------------------------------
can anybody tell me why this behaviour by compiler
Philip Nicoletti
July 1st, 2002, 01:42 PM
The first method converts x to float , converts y to float,
and does the subtraction using float arithmetic.
The second does the subtraction using "unsigned int" arithmetic,
and converts the result to float.
You are getting a "negative" number for the unsigned int subtraction.
jwbarton
July 1st, 2002, 01:45 PM
You are getting an underflow when you subtract 200 from 100 as an unsigned int. Assuming a 32 bit integer, this results in a very large positive number (4294967196). You then cast this to a float, and get 4.29497e+009.
This is the same as doing:
unsigned int x = 100;
unsigned int y= 200;
unsigned int z = x - y; // this underflows
float f = (float) z;
When you put the float cast before each number, you are subtracting 2 floats. Since floats are a signed data type, they can handle going negative. This gives you the result that you are expecting.
Best regards,
John
arunkumar_gona
July 1st, 2002, 02:02 PM
Thanks guys
Chambers
July 1st, 2002, 03:11 PM
While the answers above are absolutely correct, just for those who still don't understand, using the type:
int x = 100;
int y = 200;
instead of:
unsigned int x = 100;
unsigned int y = 200;
and then casting a conversion to float:
float z = (float) (x-y);
should produce the desired result (-100.0) since x and y can now handle the negative SIGNature.
Alan.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.