Java for 循环,加倍

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3971434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:45:42  来源:igfitidea点击:

for-loop, increment by double

javafor-loopdouble

提问by Upvote

I want to use the for loop for my problem, not while. Is it possible to do the following?:

我想对我的问题使用 for 循环,而不是 while。是否可以执行以下操作?:

for(double i = 0; i < 10.0; i+0.25)

I want to add double values.

我想添加双值。

采纳答案by rsp

To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop:

为了防止被浮点算术的工件咬住,您可能需要使用整数循环变量并在循环中导出您需要的浮点值:

for (int n = 0; n <= 40; n++) {
    double i = 0.25 * n;
    // ...
}

回答by JamesMLV

You can use i += 0.25instead.

你可以i += 0.25改用。

回答by Valchris

for(double i = 0; i < 10.0; i+=0.25) {
//...
}

The added = indicates a shortcut for i = i + 0.25;

添加的 = 表示 i = i + 0.25 的快捷方式;

回答by leonbloy

James's answer caught the most obvious error. But there is a subtler (and IMO more instructive) issue, in that floating point values should not be compared for (un)equality.

詹姆斯的回答抓住了最明显的错误。但是有一个更微妙(和 IMO 更有启发性)的问题,因为浮点值不应该与(不)相等进行比较。

That loop is prone to problems, use just a integer value and compute the double value inside the loop; or, less elegant, give yourself some margin: for(double i = 0; i < 9.99; i+=0.25)

该循环容易出现问题,只使用整数值并在循环内计算双精度值;或者,不那么优雅,给自己一些余量:for(double i = 0; i < 9.99; i+=0.25)

Edit: the original comparison happens to work ok, because 0.25=1/4 is a power of 2. In any other case, it might not be exactly representable as a floating point number. An example of the (potential) problem:

编辑:原始比较恰好可以正常工作,因为 0.25=1/4 是 2 的幂。在任何其他情况下,它可能无法完全表示为浮点数。(潜在的)问题的一个例子:

 for(double i = 0; i < 1.0; i += 0.1) 
     System.out.println(i); 

prints 11 values:

打印 11 个值:

0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

回答by Karthik

In

for (double i = 0f; i < 10.0f; i +=0.25f) {
 System.out.println(i);

f indicates float

f 表示 float

The added =indicates a shortcut for i = i + 0.25;

添加=表示 i = i + 0.25 的快捷方式;

回答by Nikhil Kumar

For integer. We can use : for (int i = 0; i < a.length; i += 2)

对于整数。我们可以用 :for (int i = 0; i < a.length; i += 2)

for (int i = 0; i < a.length; i += 2) {
            if (a[i] == a[i + 1]) {
                continue;
            }
            num = a[i];
        }

Same way we can do for other data types also.

我们也可以用同样的方式处理其他数据类型。