# help with simple type casting problem

• 02-26-2002
Jeremy_S
help with simple type casting problem
Can someone help me with this type casting problem? I've tried to simplify it as much as possible.

For example:
int rd, width
float scd, blw;

rd=7;
width=10;
blw = (float) rd/width;
scd = (int) blw*100;

blw equals 0.7000 according to the program.
scd should equal 70 but the program returns 69.

Any suggestions?
• 02-27-2002
hk_mp5kpdw
Try changing the code that assigns the value to scd to have parenthesis around the multiplication operation like so and see if that works.
Code:

`scd = (int) (blw*100);`
Incidentally when I tried the code as you provided, I got 0.7 for blw and 0 for scd, not 69.
• 02-27-2002
Salem
floats are approximations (and doubles are more accurate approximations)

Which means you can't just arbitrarily write a mathematical expression and expect to get the same computational answer.

The fact of the matter is, your intermediate answer is 69.99999, but the cast to integer simply truncates the number, no matter how close to 70 it happens to be.

Because the low order bits are lost whenever you store a float (and to a lesser extent when you store a double), these can produce different answers

blw = (float) rd/width;
scd = (int) blw*100;

And
scd = (int) ((float) rd/width)*100;

http://www.cprogramming.com/cboard/s...loat#post69676