-
Beginner
Well guys Im basicly new to C so take it ez with me >_<..
I got a project in which I had to enter a number and the computer should output if it has a factorial or not.
I dont know why but the problem I have is that when I input a number which has a factorial it says No Factorial,No FactorialNo FactorialNo Factorial then the Answer Correctly.. I wish someone could help me..
I believe the error in here..
Code:
i = 2;
facttemp = 1;
while (facttemp<=pfact){
facttemp= facttemp*i;
i++;
if (facttemp==pfact){
x = i - 1 ;
printf("\n\n\tEl numero tiene factorial, el factorial es %d", x);
return 0;}
else
printf("No tiene factorial");
getch();}
return 0;
}
-
Please add some newlines to that. It's horrible to read.
Quzah.
-
Every statement inside while loop is exeuted on every iteration, also the if/else
Till you rich the actual number - if condition is false - and you execute the else block.
So you get your "No factorial" output on every iteration...
Move it outside the loop
-
yeah I know that but how will the program know that when to post the
"No factorial" message.
The question I have is because if I move it out of the loop,
it will always print it once :(
-
Are you sure? What happens in your program when the factorial condition is matched?
Look closely at the if block of the if/else statement.
Pay attention to return
-
write a function returining int. if the number passed to that function has a factorial then it will return 1 otherwise will return 0. In your main(), call this function and pass the number you want as parameter, then use an if statement to display appropriate message.
Here is a code skeleton
Code:
int has_factoaril(int)
{
/* chechk here if it has a factorial */
/* if it has return 1*/
/* if it doesn't return 0 */
}
int main()
{
...
...
if (has_factorial(any_number))
printf("yes it has\n");
else
printf("no, it does not\n");
...
...
return 0;
}