Assuming you wanted the parameter --1
:
This generates a build error:
fat2.c:10:27: error: lvalue required as decrement operand
return n * fatqua(--1) ;
Just to be clear, lvalue
is the same as Locator value. This means that the function expects to receive an addressable value, not a constant.
Assuming you wanted the parameter --n
:
Well, here we have something interesting and your question has already been asked in stackoverflow. We have at this link and in this other some useful answers.
Some important points are highlighted here:
- Use
--n
will cause the decrease before the instruction is executed. Due to the pre-decrease, the evaluated expression will be (n-1) * fatqua(n-1)
;
- Multiplication is commutative (A * B = B * A), and this makes it dangerous when evaluating this expression. The order of assessment of the arguments is undefined in this case. So it is good practice not to use twice in the same expression a variable you are incrementing or decreasing.
If you’d like to use it --n
to solve the factor, run the code below:
#include <stdio.h>
unsigned int fatqua(unsigned int n){
printf("\nnumero : %d", n);
if (n < 2)
return 1;
return fatqua(--n) * (n+1);
}
void main() {
unsigned int n, resul = 0;
printf("Digite um numero: ");
scanf("%d", &n);
resul = fatqua(n);
printf("\n\n Fatorial de %d eh igual a: %d\n", n, resul);
}
Note that it looks horrible and very less readable that the first form (with (n-1)
in the recursive call parameter). Also, a detail would be to use unsigned int
also, since there is no factor of negative number. Snapping again, for the reasons cited, you should use
return n * fatqua(n-1);
--1
doesn’t make sense, why do it?– Maniero
@mustache I think he meant
--n
– Genos
If you mean
--n
, this is because the decrease ofn
will happen before multiplication. So whenn
for1
you will multiply the final result by0
.– bfavaretto
@bfavaretto you answered 2s before me :|
– Genos
@Genos If you want to post a more detailed answer below, feel free to ;). I stopped here.
– bfavaretto
@bfavaretto I’ll wait for the owner of the question to answer if it is
--n
. If I put it on. Thanks!– Genos
I didn’t answer because I don’t know what he wants yet.
– Maniero
--1 is equal to 1, no?
– Sorack
@Sorack ??????? is a syntax error. And if it wasn’t, it would make more sense than zero, right?
– bfavaretto
I can’t tell you, -1 in error javascript, but in C I have no idea
– Sorack
We understand the factorial perfectly, but a hint is always to indicate the input that generated the informed output. In this case, we know that 24 is 4!
– eightShirt
was --n even, vlw
– David Santos