Function that calculates the factorial of a number

Asked

Viewed 4,140 times

3

int fatorial(int n, int f){
int resultado;
while(n>1){
f=1;
resultado=(n*f);
f=f-1;
}
return (resultado);
}
int main(void){
int resultado;
int n;
int f;

printf("Digite o numero a ser fatorado:\n");
scanf("%d", &n);
resultado=fatorial(n,f);
printf("%d", resultado);
}

What error of my code does it enter loop infinite?

  • tried debugging line by line to understand?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

3 answers

2

There’s a lot of things wrong there. Most variables are unnecessary. When you’re creating code you have to ask yourself what you need it for. If you don’t have an answer don’t use it. If you can’t justify anything in the code don’t use.

I don’t understand why this parameter f in the function, it seems completely meaningless, even more that will initialize this variable there with 1, and one of the errors is to do this within the while. But if you think about what you need it for? There is already a variable that determines where the count starts and it can go down to where it wants to go. I just need another one to save the multiplication result. It makes everything simpler. And in the data request to make the factorial only needs a variable to store the required value.

#include <stdio.h>

int fatorial(int n) {
    int resultado = 1;
    while (n > 1) resultado *= n--;
    return resultado;
}
int main(void) {
    int n;
    printf("Digite o numero a ser fatorado:\n");
    scanf("%d", &n);
    printf("%d", fatorial(n));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

1

You can use recursion too.

Take a look at the example:

int factorial(int num){
    if (num == 1 || num == 0){
       return 1;
    }

   return factorial(num - 1) * num;
}

Recursion: recursion is the definition of a subroutine (function or method) that can invoke itself.

If you are starting now as a programmer at some point you will come across that word. In some cases it is legal to use it to decrease lines of code and train your logic well, but it is always good to analyze the use of memory.

0

I found some errors in your code, follow the corrected code:

int fatorial(int n){
   int aux = n - 1;

   while(aux > 1){
      n = n * aux;
      aux--;
   }

   return n;
}

int main(void){
   int resultado;
   int n;
   int f;

   printf("Digite o numero a ser fatorado:\n");
   scanf("%d", &n);
   resultado = fatorial(n);
   printf("%d", resultado);
}

Browser other questions tagged

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