Because "my program" did not increase the value 5 being that it less than 5.5

Asked

Viewed 62 times

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");
}
}
  • 2

    Incremented where? I did not understand the origin of the problem in the code.

  • 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.

  • 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

  • Because float and not int? He’s working with whole numbers.

1 answer

1


The doubt got kind of in the air, but from what I understand you want to know the reason why the is did not give another cycle.

The for in your code when we enter the value 11 does the following:

  • Initial value: 2.0 Value when cycle ends: 3.0
  • Initial value: 3.0 Value when cycle ends: 4.0
  • Initial value: 4.0 Value when cycle ends: 5.0
  • Initial value: 5.0 Value when cycle ends: 6.0

Then at the end of the last cycle it is already greater than 6 so it does not increase again.

for (float i = 2; i <= (numero / 2); i++) { //conteúdo do for... }
  1. start the variable
  2. check condition: i <= (number /2)
  3. rotates the entire contents of the for
  4. performs the post-condition: i++

for starts the variable and then stays in the cycle until the condition is no longer valid.

  • I can barely see your movements hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.