为什么要在for循环中使用double变量 [英] Why would you use double variables at all in a for-loop
问题描述
我正在阅读以下代码(在第5章继承Horstman的Core Java中):
I'm reading the following code(in ch. 5, inheritance, of Horstman's Core Java):
double dx = (to - from) / (n-1);
for (double x = from; x <= to; x += dx)
{
double y = (Double) f.invoke(null, x);
System.out.printf(%10.4f | %10.4f%n" + y, x, y);
}
为什么要在for循环中使用double变量?什么是调用
用于?谢谢
Why would you use double variables at all in a for-loop? And what is invoke
used for? thanks
编辑:f是与字段
推荐答案
这是非常好的,特别是如果你想循环通过分数值或按分数值递增。
It's perfectly fine to do, especially if you want to loop through fractional values or increment by fractional values.
然而,我只是想向其他答案添加一些东西,这就是说,如果你使用这种技术,不要与 ==
比较结束循环的条件,由于精度错误,尽管有最好的意图,这可以很容易地导致无限循环。为什么你的书的代码使用< =
。
However I just wanted to add something to the other answers, which is that if you employ this technique, do not compare with ==
for the condition to end the loop. Due to precision errors, this can easily result in an infinite loop in spite of the best intentions. That's why your book's code uses <=
.
这篇关于为什么要在for循环中使用double变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!