Small Error??
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 UTC
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! ...
Jan 29, 2017 at 8:34pm UTC
Okay, kemort. I tried to fix that by resetting
int result .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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;
numb--;
counter--;
result = 1;
}
}
Now it kind of works
5
5! = 120
4! = 24
3! = 6
2! = 2
1! = 1
Yay! Now, I just need to show the math in the output...
Jan 29, 2017 at 9:34pm UTC
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
#include <iostream>
using namespace std;
int main()
{
int counter = 0;
int numb = 0;
cout << "Enter integer (enter non numeric input to quit): " ;
long long result = 1;
while (cin >> numb)
{
counter = numb;
if (numb == 0)
{
cout << "0! = 1" ;
}
while (counter!=0){
for (int i = 1; i <= counter; i++)
{
result = result * i;
}
cout << counter << "! = " << result << endl << endl;
counter--;
result=1;
}
cout << "Enter integer (enter non numeric input to quit): " ;
}
cout << "Done" << endl << endl;
return 0;
}
Enter integer (enter non numeric input to quit): 5
5! = 120
4! = 24
3! = 6
2! = 2
1! = 1
Enter integer (enter non numeric input to quit):
Topic archived. No new replies allowed.