My factorial function does not return the expected value! C language

6

My teacher is starting to go through functions, and asked us to do a factorial function of a number, but it always returns the wrong value and I do not know what happens.

Code:

int fatorial(int n) {
 int ans = 1;

 while(n>1){
  ans*=n; n--; return ans;
 }

}
    
asked by anonymous 26.08.2018 / 18:39

1 answer

6

Good friend, from what I saw your function is 90% correct, however you are returning the ans value before it is completely correct ... You must multiply all the numbers to then return- it ...

Example:

int fatorial(int n) { int ans = 1;

while(n>1){ ans*=n; n--; }
 return ans;
}
    
26.08.2018 / 18:40