Java - problem when factorial using while

Asked

Viewed 31 times

-1

The idea is to type I type 3 numbers and calculate the factorial of each number. But I didn’t understand why the variable is keeping the value, for example.

    String entra;
    int cont = 1;
    int numero = 0;
    int fatorial = 1;
    int contFat =1;
    
    while(cont <= 3){
        entra = JOptionPane.showInputDialog("Insira um numero: ");      
        numero = Integer.parseInt(entra);
        cont++;
    
        while(contFat <= numero)
        {
            fatorial = fatorial + (fatorial*(numero-1));
            numero--;   
        }
        
        System.out.println("resultado da fatorial é: " + fatorial);

    }

resultado da fatorial é: 6
resultado da fatorial é: 12
resultado da fatorial é: 12

in the case I typed the numbers in order 3,2,1. The factorial of the second number that should be 2, multiplied by 6 (result of the first factorial).

  • I suggest you don’t count, so he can learn to make one table test.

  • as I mentioned, I understood that the factorial number(2) * (6)= 12. But what I was looking for was the second result inform me the factorial of 2 only and if it was possible to do this with only these variables, because if there were 30 numbers, I would have to declare 30 variables, but thank you

  • Tell me what’s so special about variables entra and numero that you don’t need to have several of them and fatorial you think you need to. I repeat, if you simulate the operation of the algorithm manually with a desktop test you will understand.

  • Perhaps what you are missing is the notion that the declaration of a variable can be separated from the initialization. Example: int minhaVariavel; minhaVariavel = 2; and that both can be placed in different regions of the code.

No answers

Browser other questions tagged

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