I think it wants you to explicitly declare the return type in a recursive function.
function factorial (n) : int
{
if(n==0) return(1);
return (n * factorial (n-1) );
}
print(factorial(5));
Thanks! i didnt find "return" in the unity reference only things like "onkey.return" so i thought it might be something different, and also the "if" has no curly brackets after it so i was totally out of my depth. interestingly, factorial 1.2 crashes unity, unity just dissapears... so it must be an infinite feedback loop? and factorial 13 is out of range of int32..
1.2 is a float. And that's technically allowed but, you should probably add a type to n so that doesn't happen. function factorial (n : int) : int { that way no one can pass a float and get an infinity loop.
for those of you learning JS etc, there are no unity tuts on unity recursive, so here are recursive functions and links for learning:
Factorial Complete:
var number = 5.5;
function factorial(n) : int
{
// If the number is not an integer, round it down.
n = Mathf.Floor(n);
// The number must be equal to or bigger than zero
if (n < 0)
{
return (0);
}
if ((n == 0) || (n == 1))
{ // If the number is 0 or 1, its factorial is 1.
return (1);
}
else
{ // Make a recursive call
return (n * factorial(n - 1));
}
}
print(factorial(number));
Fibonacci in unity:
function Fibo(n) : int
{
if((n==1)||(n==2)) return 1;
else return Fibo(n-1) + Fibo(n-2);
}
print(Fibo(8));
good page for JS recursion, in the end i think they do a JS maze generator!
Thanks! i didnt find "return" in the unity reference only things like "onkey.return" so i thought it might be something different, and also the "if" has no curly brackets after it so i was totally out of my depth. interestingly, factorial 1.2 crashes unity, unity just dissapears... so it must be an infinite feedback loop? and factorial 13 is out of range of int32..
– anon270641571.2 is a float. And that's technically allowed but, you should probably add a type to
– Peter_Gnso that doesn't happen. function factorial (n : int) : int { that way no one can pass a float and get an infinity loop.I suggest making that int unsigned. (uint). I can still pass -1 to that and crash it.
– CHPedersenJust make that conditional a <= and we don't have to worry about any of this and we can move on. if( n <= 0) return 1;
– Peter_G