简体   繁体   中英

Print on last iteration of for loop

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

  double bg = 5.0;
  double f = 0.0;
  for(double i = 0; i <= bg; i += 1)
    {
        f = f + ((2 * i + 1)*0.1);

        if (Math.abs(i - bg) < 0.00001f)
        {
            System.out.printf ("%.1f" , f);
        }
    }

Floating-point numbers don't have exact representations for all the numbers you think they might. For example, when dividing 1 by 3, you get 0.333... since you use decimal numeric system.

However, computers use binary, so even though 0.1 seems like an easy and exact number to write, in binary it looks more like 0.0001100011..., and so on to infinity. And, since computers don't have infinite memory, this number is rounded to the closest possible representation. That's why the exact comparison does not work.

There are a number of ways to deal with this problem. One option is to use the delta comparison that's already been mentioned. However, if you know that you'll only be dealing with numbers of up to digits after the decimal point, you can instead multiply everything by 100 use integer numbers instead. This is the advised way if you're doing monetary calculations, for example.

In my graphical tools I'll iterate over an integer value and calculate the floats on the fly:

int bg = 5;
double f = 0.0;
for(int i = 0; i <= bg; i += 1) {
    f = f + ((2 * i + 1)*0.1);

    if(i == bg)
    {
        System.out.printf ("%.1f" , f);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM