Error when trying to calculate the factorial, by parameter passage

0

I'm studying functions by passing the parameter, the teacher asked to calculate the factorial of a number per pass parameter, the maximum I got was the code below, even though the code does not execute.

#include <stdio.h>
#include <stdlib.h>
void fatorial(int num, long int*fat); 
int main()
{

  int num;
  printf("Digite um numero:\n");
  scanf("%d", &num);
  fatorial(num);
  return 0;
}
void fatorial(int num, long int *fat)
 {
    for(fat = 1; num > 0; num = num - 1)
    {
       fat *= num;
    }
    printf("%ld\n", fat);
 }
    
asked by anonymous 07.12.2017 / 22:27

1 answer

0

Refine your example by taking the long int *fat parameter of your factorial function and declare fat as the local variable in the function.

#include <stdio.h>
#include <stdlib.h>
void fatorial(int num); 
int main()
{

  int num;
  printf("Digite um numero:\n");
  scanf("%d", &num);
  fatorial(num);
  return 0;
}

void fatorial(int num)
 {        
    long fat = 0;    
    for(fat = 1; num > 1; num--)
        fat *= num;             
    printf("%ld\n", fat);
 }

Another change would be to make the factorial return a long, thus

#include <stdio.h>
#include <stdlib.h>
long fatorial(int num); 
int main()
{

  int num;
  printf("Digite um numero:\n");
  scanf("%d", &num);
  long fat = fatorial(num);
  printf("%ld\n", fat);
  return 0;
}

long fatorial(int num)
 {
    long fat = 0;
    for(fat = 1; num > 1; num--)
        fat *= num;    
    return fat;
 }
    
07.12.2017 / 23:07