I’ve got a little question concerning a FOR cycle I’ve seen today. It looks like this :
for (double i = 0.0; i < 1.0; i += 0.1) {
for (double j = i; j < 1.0; j += 0.1) {
double k = i + j;
if ((k % 1) == 0) {
System.out.println(i + " + " + j + " = " + k);
}
}
}
It’s supposed to output the sums of two numbers between 0 and 1 (incremented by 0.1) that are equal to a whole number. However, for some reason it does not show the 0.1 + 0.9 = 1.0 sum. My guess is it could be because of incorrect representation of the numbers in double format (i. e. the 0.3 + 0.1 isn’t 0.4, but rather something like 0,399999999).
Can anyone possibly confirm this is really the issue and advise how to correct it? Any help appreciated greatly!
Why don’t you use
ints – start from0till10with a step of1? And thenif (k % 10) == 0