Jan 29, 2017 at 7:52pm Jan 29, 2017 at 7:52pm UTC
I'm writing a program that does factorials. It is supposed to cout all the factorials up to the integer that the user enters. Example:
Input
Enter integer (enter non numeric input to quit):
Output
1! = 1 = 1
2! = 2 x 1 = 2
3! = 3 x 2 x 1 = 6
4! = 4 x 3 x 2 x 1 = 24
5! = 5 x 4 x 3 x 2 x 1 = 120
I think I did something wrong with my while loop on lines 20-29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
using namespace std;
int main()
{
int counter = 0;
int numb = 0;
cout << "Enter integer (enter non numeric input to quit): " ;
cin>>numb;
counter = numb;
long long result = 1;
while (cin >> numb)
{
if (numb == 0)
{
cout << "0! = 1" ;
}
while (counter!=0){
for (int i = 1; i <= numb; i++)
{
result = result * i;
}
cout << numb << "! = " << result << endl << endl;
counter--;
}
cout << "Enter integer (enter non numeric input to quit): " ;
}
cout << "Done" << endl << endl;
}
If you input 5, output is
5! = 120
4! = 2880
3! = 17280
2! = 34560
1! = 34560
Last edited on Jan 29, 2017 at 8:05pm Jan 29, 2017 at 8:05pm UTC
Jan 29, 2017 at 8:18pm Jan 29, 2017 at 8:18pm UTC
Instead of resetting result to 1 at the start of each new number, you are continuing to multiply it. eg you calculate 5! ok but for 4! you are multiplying 4! by 5! ...