1
I’m starting in programming and always trying to figure out the things that are not clear, so far I managed, but this one I tried and tried and I can not understand why the program did not increase the value 5 being that it less than 5.5
public class Primo {
public static boolean ehPrimo(float nr) {
if (nr < 2)
return false;
for (float i = 2; i <= (nr / 2); i++) {
if (nr % i == 0)
return false;
System.out.println("nr = " + nr + "\ti = " +i);
}
return true;
}
public static void main(String[] args) {
float x = 11f;
if (ehPrimo(x)) // se for primo
System.out.println(x + " e primo");
else // se não for primo
System.out.println(x + " não e primo");
}
}
Incremented where? I did not understand the origin of the problem in the code.
– user28595
The code is okay, I’m just trying to understand it better. In a loop step 'i' is set to '5' and 'nr' 11 ( nr / 2 ) is set to 5.5 In the case when 'i' is <= a 5.5 it should increment 'i' making it '6' and then when it was going to check if 'i' now '6' was not <= 5.5 it would stop the loop, but the loop for the with 'i' worth '5' being that it is 5 <= 5.5 condition in which it should continue the loop. Thank you for your attention, Blame anything.
– Eduardo D. Oliveira
No, the loop stops at 6.0, as 6.0 is greater than 5.5. So it no longer enters the loop and does not display System.out.println. So much so that the last output displayed is nr = 11.0 i = 5.0, as it was the last time it entered the loop. At least that was the result in ideone
– user28595
Because
float
and notint
? He’s working with whole numbers.– Dan Getz