-
Strange Output
Hello world,
I'm studying functions and recursions. I'm trying to write functions that evaluates the power and the factorial - the very common exercise -. But, some strange output appears..
Here's the code:
Code:
#include <stdio.h>
int absolute(int num)
{
if(num > 0)
return num;
else
return -num;
}
int loop_factorial(int num)
{
long int f = 1;
while(num > 1)
f *= num--;
return f;
}
int recursive_factorial(int num)
{
if(num == 1)
return num;
else if(num <= 0)
return 1;
else
return num * recursive_factorial(num - 1);
}
float loop_power(int num, int pow)
{
if(num == 0)
return 0;
if(pow == 0)
return 1;
int counter = 1;
while(counter++ < absolute(pow))
num *= num;
if(pow>0)
return num;
else
return 1/num;
}
int main(void)
{
char choice;
int num, opt;
while(1)
{
printf("Enter function: ");
choice = getchar();
if(choice == 'f')
{
choice = getchar();
if(choice == 'r')
{
printf("Enter: ");
scanf("%d", &num);
printf("%d! = %d\r\n", num, recursive_factorial(num));
}
else if(choice == 'l')
{
printf("Enter: ");
scanf("%d", &num);
printf("%d! = %d\r\n", num, loop_factorial(num));
}
}
else if(choice == 'p')
{
printf("Enter: ");
scanf("%d %d", &num, &opt);
printf("%d^%d = %f\r\n", num, opt, loop_power(num, opt));
}
}
return 0;
}
And here's what I have tried:
http://img808.imageshack.us/img808/4531/errornzh.png
Uploaded with ImageShack.us
Notes:
- I have shown that the factorial ( both versions ) are working fine.
- Why 2 of "Enter function: "?
- why when using big numbers functions crash? ( I think that has something to do with the type of the return, but I have changed the type to long double but that fixed nothing )
Any help?
Thanks in advance :)
-
You need to compute with long doubles, not just try to convert at the end.
Also, "enter-key" is a character, so getchar() reads the enter-key, tries to process it, and can't, so your loop prints the prompt again.