Factorial function does not return

Asked

Viewed 401 times

0

I need to use function in C but is not returning the factorial.

Problem:"Given an integer n, calculate its factorial n!. The factorial of a number is given by the equation:

n! = n(n1)(n2) : : : 1. Por definição, 0! = 1.

You must implement the function:

1 /** 2 * Function that calculates the factorial of a number n
3 * @param n a positive integer
4 * @re-factorial of n
5 */
6 unsigned long int fat( unsigned int n);

Input The program must read an integer number n. Output The program must display a line with the message: "n! = f", where n is the number read e f its factorial. Observations The factorial of a number is the result of a productive operation that can lead to incredibly high values great. Remember to use appropriate data types to the problem proposed."

My code:

#include <stdio.h>
#include <stdlib.h>

unsigned long int fat( unsigned int n){
  int x,fatorial,resultado1;

  for(fatorial = 0; x > 1; x = (x - 1)){
    fatorial = (fatorial * x);
    resultado1=fatorial;
    }
    return resultado1;
}


int main(){
  int numero,resultado;

  scanf("%d",&numero);

    resultado = fat(numero);
  printf("%d! =  %d",numero,resultado);


    return 0;

}

2 answers

2


The code is confusing, disorganized and has too many things. But the main problem is mixing concepts without criterion. The statement demonstrates what it has to do. The factorial is a number multiplied once followed by another by a sequence of numbers. This sequence goes from 1 to the specified N. So the loop is very simple, it goes from 1 to N, it is in the statement. And the multiplication is the initial value of 1 (the basic unit) by that value being incremented. Only this.

There was also a formatting problem on printf().

I suggest understanding the mechanisms of language in a more basic way before using them. I mean, knowing each character of the for and other things. Because you’re putting everything. Don’t do anything without discretion, without being able to explain why you’re doing it. Do not put a comma, a space without a justification. The same omit certain things.

#include <stdio.h>

unsigned long int fat(unsigned int n) {
    int fatorial = 1;
    for (int i = 1; i <= n; i++) fatorial *= i;
    return fatorial;
}

int main() {
    int numero;
    scanf("%d", &numero);
    printf("%d! = %ld", numero, fat(numero));
}

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

0

I think it’s easier this way: he checks the condition, if it’s true do what’s left of ':'. If not, then do what’s right of ':'.

//fatorial
int fatorial(int num){
    return (num>0) ? num*fatorial(num-1) : 1;
}

Browser other questions tagged

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