Assignment Help

I'm new to the site today and need a little help with some homework. I am by no means looking for anyone to give me the answers, just to point me in the right direction. With that said I'm trying to write a function to calculate the factorial of a number using a FOR loop and it keeps giving me an answer of 0. Can someone please tell me what I'm doing wrong.

#include <iostream>
using namespace std;

double factorial (double num);

int main()
{
double num;
double answer;
char yesno = 'y';

while ( yesno == 'y')
{
cout << " Please enter a number: ";
cin >> num;
cout << " The Factorial of " << num << " is " << answer << "\n\n";

do {
cout << " Would you like to enter another number?(answer y or n) ";
cin >> yesno;
cout << "\n";
} while ( yesno != 'y' && yesno != 'n');
}
system("pause");
return 0;
}

double factorial (double num)
{
double answer=1;
for(double i=1; i<=num; num--)
answer = answer*num;
return answer;
}

Thank you!
And if I'm posting wrong can someone let me know that also.

Last edited on
You never call factorial
I understand what you are trying to do with your factorial function but it is a really odd/not ideal way to write the for loop...

you also need to add {} so that the for loop executes until it is satisfied and then after that returns answer. Ass you currently have it set it just returns answer without executing the for loop fully.

Also your do while loop where you ask if the user wants to add another input does not work correctly. Take a look at the logic behind your while statement and rework that part.
Ahhhh!
I deleted the variable "answer", then replaced answer in main with factorial(num).
Works perfectly!

Thank You
Can you post your final code that is working? Nvm, works perfectly.
Last edited on
gh24

I went ahead and declared "i" outside the for loop. Is this considered more ideal?

Also added the {} to the for loop. it now allows for greater integers, before it wouldnt' calculate large numbers.

Looked at logic in the do while loop. Any hints behind the logic there? I did the extra space on purpose if that's what you're referring to? I just like the spaces between lines.

Thanks for your help.
I was messing around with your code and made some asthetic changes that messed with the logic of the while loop, it was an error on my end, not yours. I ran the code and it works great. I wouldn't worry about it. In regards to the for loop I just don't like using num-- in that instance. It serves a dual purpose for you but it is easy to mess up IMHO. I would have made it more like:

1
2
3
4
5
6
7
8
9
double factorial (double num)
{
double answer=num;	
for(int i=1; i<num; i++)

answer = answer*(num-i);

return answer;
}


Last edited on
Thanks for the info. I'll make a not for next time.
Topic archived. No new replies allowed.