This code has no logic whatsoever.
It even starts well, except by creating unnecessary variable again.
To call the function you need to be parentheses and pass as argument the number typed to be able to perform the calculation.
You have to check the return of this function if it is negative. If it is, you have to give the error message. If you see a natural number you can print.
Try to keep the code organized that helps you understand it.
You’re still missing some basic syntax and concepts variables, parameters, arguments, scope, function, etc..
#include <stdio.h>
int fatorial(int num) {
if (num >= 0) {
int fat = 1;
while (num > 0) {
fat *= num;
num--;
}
return fat;
} else {
return -1;
}
}
int main() {
int num;
printf("ESTE POGRAMA CALCULA N FATORIAL = N!\n");
printf("Digite um valor para ser calculado: ");
scanf("%d", &num);
int fat = fatorial(num); //chama a função passado o que foi digitado e guarda em fat
if (fat < 1) { //verifica se o retorno é menor que 1, se for indica erro
printf("O calculo do fatorial se aplica somene aos numeros naturais.\n");
} else { //se fat não for menor que um, então pode imprimir o resultado
printf("\n\tO fatorial de %d = %d\n\n", num, fat);
} //encerrou o bloco do if, só executa um dos dois blocos, nunca ambos
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Ah this one has on the internet, it is much leaner, but the first one from the top helps to clarify better for those who are beginner, with for, while... but anyway thank you.
– André