___ erkimt ___ How to test the factorial in Main ()? ______ qstntxt ___
How would %code% of this function be? The user types a number and the factorial of the number appears on the screen.
#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
}
This code has no logic at all.
To get well, except for the fact that create unnecessary variable again.
To call the function needs to be with brackets and pass as argument the number entered in order 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.
Still missing some syntax basics and concepts of variables , parameters, arguments , scope , functions, 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
}
See Running on ideone . And No Coding Ground . Also put it on GitHub for future reference .
Here is a recursive function and an iterative function, where both calculate the factorial
%pre%
PS1: Learn recursive functions, once I got an IT stage because I was the only one who used recursive functions in the selection test
PS2: Oh, and if you're just starting out, I'll tell you to study clean code