Function that calculates the factorial of a number [closed]

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 is the error of my code that makes loop infinity?

    
asked by anonymous 02.10.2018 / 23:46

3 answers

2

There's a lot wrong with it. Most variables are unnecessary. When you are creating the code you have to ask yourself why you need it. If you do not have an answer do not use. If you can not justify anything in the code do not use.

I do not understand why this parameter f in the function, seems completely meaningless, even more that it will initialize this variable there with 1, and one of the errors is to do this within while . But if you think hard about what you need it for? It already has a variable that determines where the count starts and can go down until it reaches where it wants. I just need one to save the multiplication results. It's all simpler. And in the data request to do the factorial only need a variable to save 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));
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
03.10.2018 / 00:03
1

You can use recursion as well.

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 as a programmer at some point you will come across this word. In some cases it's cool to use it to shrink lines of code and train your logic well, but it's always good to analyze memory usage.

    
05.10.2018 / 17:54
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);
}
    
05.10.2018 / 19:59