'for-loop, increment by double
I want to use the for loop for my problem, not while. Is it possible to do the following?:
for(double i = 0; i < 10.0; i+0.25)
I want to add double values.
Solution 1:[1]
You can use i += 0.25 instead.
Solution 2:[2]
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.
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)
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:
for(double i = 0; i < 1.0; i += 0.1)
System.out.println(i);
prints 11 values:
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
Solution 3:[3]
for(double i = 0; i < 10.0; i+=0.25) {
//...
}
The added = indicates a shortcut for i = i + 0.25;
Solution 4:[4]
In
for (double i = 0f; i < 10.0f; i +=0.25f) {
System.out.println(i);
f indicates float
The added = indicates a shortcut for i = i + 0.25;
Solution 5:[5]
For integer.
We can use : 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.
Solution 6:[6]
private int getExponentNumber(double value){
String[] arr;
String strValue = String.valueOf(value);
if (strValue.contains("E")){
arr = strValue.split("E");
return Math.abs(Integer.parseInt(arr[1]));
}
else if (strValue.contains(".")){
arr = strValue.split("\\.");
return arr[1].length();
}
return 0;
}
private int getMinExponent(int start, int stop, int step){
int minExponent = Math.max(Math.abs(start), Math.abs(stop));
minExponent = Math.max(minExponent, Math.abs(step));
return minExponent;
}
double start = 0;
double stop = 1.362;
double step = 2E-2;
int startExp = getExponentNumber(start);
int stopExp = getExponentNumber(stop);
int stepExp = getExponentNumber(step);
int min = getMinExponent(startExp, stopExp, stepExp);
start *= Math.pow(10, min);
stop *= Math.pow(10, min);
step *= Math.pow(10, min);
for(int i = (int)start; i <= (int)stop; i += (int)step)
System.out.println(i/Math.pow(10, min));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | iHiD |
| Solution 2 | |
| Solution 3 | Wayne |
| Solution 4 | Jean-Philippe Briend |
| Solution 5 | Nikhil Kumar |
| Solution 6 | mojtaba |
