...

View Full Version : Float Division Problems (C)



MattJakel
01-24-2005, 03:54 AM
I have a segment of code that takes an integral float and divides it by ten however many times it's necessary to make it less than one (therefore moving all digits to the right of the decimal). For some reason, I can't get it to work correctly. Here are two different approaches, neither of which works:



/*printfs added for testing*/
printf("decval is %f\n", decval);
while((decval /= 10) > 0)
;
printf("decval is %f\n", decval);


This one, when tested with a decval of five, prints the following:

5.000000
0.000000

I thought that the assignment in the condition might have been messing things up, so I tried the following:



/*printfs added for testing*/
printf("decval is %f\n", decval);
while((decval /= 10) && decval > 0)
;
printf("decval is %f\n", decval);


This did the exact same thing.

I then thought that maybe there was something wrong with float division, so I changed the first printf to print decval/10, which showed the correct answer of 0.500000... but the while loop still changed it to 0.000000.

What is it that I'm missing here? I am relatively new to C, but I'm surprised to be having these problems with seemingly simple float division...

Thanks,
Matt

aman
01-24-2005, 07:02 AM
here, try this instead..


int main()
{
float decval = 5.0f;
printf("decval is %f\n", decval);


while ( (decval = (decval / 10.0f)) > 0 )
{
printf("decval is %.64f\n", decval);
}

return 0;
}


or remove the ';' after your while loop...

shmoove
01-24-2005, 09:54 AM
Your condition is wrong.


divides it by ten however many times it's necessary to make it less than one

But instead of having a condition of "keep dividing while greater or equal than one" your condition is "greater than 0".
Try:


while((decval /= 10) >= 1)
;

instead.

shmoove

aman
01-24-2005, 10:18 AM
ahh I missed that part, good catch shmoove

MattJakel
01-25-2005, 02:57 AM
Wow I feel stupid. ;) I can't believe I made such a dumb mistake with a loop! Oh well, thanks for the help!

Matt



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum