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.
tried debugging line by line to understand?
– Ricardo Pontual
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.
– Maniero