Having a hard time trying to figure out why my code doesn't return anything. I want it to return '3628800' as 10! (factorial). Any help is appreciated.
#include <stdio.h>
void ft_iterative_factorial(int nb);
int main()
{
ft_iterative_factorial(10);
return 0;
}
void ft_iterative_factorial(int nb)
{
int i;
int fact;
int num;
fact = 1;
if (num <= 0)
fact = 1;
else
{
i = 1;
while (i <= num)
{
fact = fact * i;
i++;
}
}
}
You need to specify a return type, so you would have something like this.
#include <stdio.h>
int ft_iterative_factorial(int nb);
int main()
{
int num;
num = ft_iterative_factorial(10);
return 0;
}
int ft_iterative_factorial(int nb)
{
int i;
int fact;
int num = nb;
fact = 1;
if (num <= 0)
fact = 1;
else
{
i = 1;
while (i <= num)
{
fact = fact * i;
i++;
}
}
return fact;
}
Hi your function 'ft_iterative_factorial' does not have a return type. Function should have a return type to return some value to the calling function. Also you are not using the passed parameter 'nb' anywhere in your factorial function.
Here is the corrected code:
#include <stdio.h>
//function should have a return value to return something
int ft_iterative_factorial(int nb);
int main()
{
printf("%d",ft_iterative_factorial(10));
return 0;
}
int ft_iterative_factorial(int nb)
{
int i;
int fact;
int num = nb;// You have not assigned nb to num
// In your case num is not initailised
fact = 1;
if (num <= 0)
fact = 1;
else
{
i = 1;
while (i <= num)
{
fact = fact * i;
i++;
}
}
return fact;
}
If the code compiles, you should simulate the execution of your program step by step:
main
function;ft_iterative_factorial
, with argument 10
;fact
is initialized to 1
;ft_iterative_factorial
, and therefore discards all variables declared within its scope... ... and here is the problem: the value of fact
is lost.
If you want that value to be passed back to main function you should for example declare the function ft_iterative_factorial
as
int ft_iterative_factorial(int nb);
and add
return fact;
at the end of its body.
My function isn't returning anything but does compile and seems correct
Your code is not correct at all. In order to check that just print the value of fact
inside your ft_iterative_factorial
function. By change the return type from void
to int
, you could solve your return issue but I think you should check the body of ft_iterative_factorial
carefully.
Hint::
void ft_iterative_factorial(int nb) //<---change the return type to int
{
int i;
int fact;
int num;
fact = 1;
if (num <= 0) //<-----what is num????? should be nb
fact = 1;
else
{
i = 1;
while (i <= num) //<-----what is num????? should be nb
{
fact = fact * i;
i++;
}
}
//<------ just add return statement
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.