Operating System - HP-UX
1834804 Members
2702 Online
110070 Solutions
New Discussion

adding numbers don't add up..

 
SOLVED
Go to solution
Dave Chamberlin
Trusted Contributor

adding numbers don't add up..

I have a small C program that adds .01 to a number X times.
If the number is 1000, the result is 10.00, for 10000 the result is 100.00 but for higher numbers, the result is not correct (x=100000 gives 1000.67, x=1000000 gives 9865.22). What gives?
4 REPLIES 4
Sachin Patel
Honored Contributor

Re: adding numbers don't add up..

Hi Dave,
try double or long I am not sure. It is been long time.

long flot x;

Sachin
Is photography a hobby or another way to spend $
Kenneth Platz
Esteemed Contributor

Re: adding numbers don't add up..

Dave,

What datatype are you using for your additions? If you're currently using a "float", then you may want to try using a "double" or "long double", because those have greater precision.

I hope this helps.
I think, therefore I am... I think!
Rodney Hills
Honored Contributor

Re: adding numbers don't add up..

Due to the way floating point numbers are represented, the concept of precision is taken with a grain of salt.

If you wish to calculate to exactly 2 decimal places, then scale an integer number (ie instead of 1.23 of "real" type, use 123 in integer). Thus in calculations your results will be precise. Convert to "real" only for printing.
There be dragons...
Andreas Voss
Honored Contributor
Solution

Re: adding numbers don't add up..

Hi,

setting

double f=0.0;

is sufficient.

Regards