Trouble with floats and doubles

Hello. I just noticed some interesting results. Below is a simple program that repeatedly adds 0.1 to a variable called __sum__.

Code:

`public class Sum {`

public static void main(String[] args) {

float sum = 0;

for (int i = 0; i < 10; i++) {

sum += 0.1;

}

System.out.print(sum);

}

}

I expect the resulting print out to be 1.0. Instead, I get 1.0000001. When I change the variable __sum__ from a float to a double, I get a result of 0.9999999999999999.

I don't understand why declaring the variable __sum__ to be a float gives me a value larger than I expected, and when declaring the variable __sum__ to be a double, I get a value less than I expected.

Can anyone explain this to me? Thanks, and my apologies for the silly question.

Re: Trouble with floats and doubles

Re: Trouble with floats and doubles

Yikes - I guess I have some reading to do.

Thanks for your reply and the helpful link.

"Hersch lookin' at you, kid."