Factor function in C does not return result

3

What's wrong with my code?

int fatorial (int n, int num, int fat) 
{
    if(num >= 0)
    {
        fat = 1;
        n = num;

        while(n > 0)
        {
            fat *= n;     //FATORIAL = FATORIAL*N
            n--;
       }
    }
}
    
asked by anonymous 21.02.2017 / 14:08

2 answers

5

The function is not returning anything, whether the value is valid or not. I used -1 to indicate error.

In addition, you are using completely unnecessary parameters: fat can be local and n simply does not even need to be a local variable.

#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(void) {
    printf("%d\n", fatorial(0));
    printf("%d\n", fatorial(1));
    printf("%d\n", fatorial(5));
    printf("%d\n", fatorial(-5));
}

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

    
21.02.2017 / 14:28
1

By default, C returns 0 for a function without return, for example the int teste() { } function has no compile error, because the C language returns zero as a default return. Then the function becomes:

int teste() {
  return 0; // código adicionado pelo compilador C
}

In your role:

int fatorial (int n, int num, int fat) 
{
    if(num >= 0)
    {
        fat = 1;
        n = num;

        while(n > 0)
        {
            fat *= n;     //FATORIAL = FATORIAL*N
            n--;
        }
    }
    return 0; //adicionado pelo compilador
}
    
21.02.2017 / 14:35