double temp = 0;
for (int i = 0; i < 20; i++)
temp += 0.05;
I thought the value of temp must be 1.0. But when I debug my program, I saw the value of temp was 1.0000000000000002.
I
don't know why temp has a value like that. Anyone can explain it for
me? I need to use the true value of temp (1.0) to compare with 1.
Loading
kPosted Dec 4, 2008, 1:13 AM
AlanPosted Dec 3, 2008, 2:23 PM
It's because floating point numbers don't usually have an exact representation in the machine and operations involving them can therefore produce rounding errors.
If you want to avoid these problems, use the decimal type instead:
decimal temp = 0m;
for (int i = 0; i < 20; i++)
temp += 0.05m;
The drawbacks are that decimals require twice as much memory (16 bytes instead of 8 for double), don't have as big a range and produce slower code. However, in most applications, these disadvantages are unimportant.