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

Asked

Viewed 41 times

6

My teacher is starting to pass 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;
 }

}

1 answer

6

Good friend, from what I saw your function is 90% correct, but you are returning the value ans 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;
}
  • That’s right, but I’m a fool, thank you.

Browser other questions tagged

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