简体   繁体   English

在for循环的最后一次迭代中打印

[英]Print on last iteration of for loop

So I have a simple for loop: 所以我有一个简单的for循环:

  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. 当我为每个实例将i递增1时,它可以正常工作。 But when i do i += 0.1 it doesn't print f. 但是当我做我+ = 0.1时它不会打印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 如果(Math.abs(i-bg)<0.00001f)//0.00001f是非常小的值-几乎为零,请选择此值以满足您的需要

For more look at http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm 有关更多信息,请访问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. 例如,将1除以3​​时,将得到0.333 ...,因为您使用的是十进制数字系统。

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. 但是,计算机使用二进制,因此即使0.1看起来是一个简单而准确的数字,但二进制看起来更像0.0001100011 ...,依此类推,直到无穷大。 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. 但是,如果您知道只处理小数点后的数字,则可以用整数代替100。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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