-
Help with for loop
im trying to make a little dos app that finds the factorial of the number the user enters.
when i type in the number 7, i get 840, when i should be getting 5040.
here is my source:
Code:
#include <iostream>
using namespace std;
int num;
void calculate();
void last();
int main()
{
cout<<"Please enter the number you wish to find the factorial of: ";
cin>> num;
calculate();
}
void calculate ()
{
const int sent = num;
for (int x = 1; x < sent - 1; x++){
num = num * x;
}
last();
}
void last()
{
int input;
cout<<"The answer is: " << num <<" \n";
cin.get();
cout<<"\n Would you like to enter another number?\n\n1.)Yes\n2.)No\n\nSelection:";
cin>> input;
switch (input){
case 1:
cin.get();
main();
break;
case 2:
cout<<"Thank you for using this program. Have a nice day.\n";
cin.get();
break;
}
}
-
Check the logic of your loop condition:
x < sent - 1
This will terminate if x == sent - 1, and hence, that number will not get multiplied in.
Cheers
-
Change that to either of the following:
-
-
Adam Sandler said it best:
You're gonna die, clown!
-
thanks guys. :)
i had originally put that there, but changed it cause i thought it wouldnt work :p maybe i should have tested it 1st.
-
>>>maybe i should have tested it 1st.
Always a good idea. I've done that several times and ended up spending two hours fixing something I had right the first time.