So I have a simple for loop:
double bg = 5.0;
double f = 0.0;
for(double i = 0; i <= bg; i += 1)
{
f = f + ((2 * i + 1)*0.1);
if(i == bg)
{
System.out.printf ("%.1f" , f);
}
}
When I increment i with 1 for each itiration it works fine.
But when i do i += 0.1 it doesn’t print f.
Any ideas why?
You can not compare floats like that.
Usually equality of two floats(doubles) is checked with something like
if (Math.abs(i – bg) < 0.00001f) //0.00001f is very small value – almost zero, pick this value to suit your needs
For more look at http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
Your code should look like