Click to See Complete Forum and Search --> : hmm.. whats wrong?


bobtcowboy
12-05-2001, 10:58 PM
I'm a newbie C programmer here...

I'm trying to pass a value of 4 to a recursive function that gets the factorial value... for some reason, the value of "n" is reported as 0.0 when I get into the "nFact" function

the relevent bit from main.c


(void)printf(" The factorial of %d is %d\n",4, nFact(4));


in a file called nfact.c



int nFact(n)
float n;
{
if (n == 0)
return (1);
else
return (n * nFact(n-1));
}



Any help?

[ 05 December 2001: Message edited by: bobtcowboy ]

The Kooman
12-05-2001, 11:54 PM
Originally posted by bobtcowboy:
<STRONG>I'm a newbie C programmer here...

I'm trying to pass a value of 4 to a recursive function that gets the factorial value... for some reason, the value of "n" is reported as 0.0 when I get into the "nFact" function

the relevent bit from main.c


(void)printf(" The factorial of %d is %d\n",4, nFact(4));


in a file called nfact.c



int nFact(n)
float n;
{
if (n == 0)
return (1);
else
return (n * nFact(n-1));
}



Any help?

[ 05 December 2001: Message edited by: bobtcowboy ]</STRONG>

You are computing a float value but returning it from the function as an int without type-casting it!

You should either take an int argument (since factorials for floats don't make sense) and return an int i.e change your nFact function to:

int nFact(n)
int n;

or
return float from nFact and print it as a float and not an int:

float nFact(float n)
{ /* blah */ }

/* inside main() */
printf("blah %f\n", nFact(4.0));


or typecast the return value of nFact to int:

int nFact(n)
float n;
{
if (n == 0)
return (1);
else
return (int)(n * nFact(n-1));
}


HTH