+ 1

Factorial Output error

#include <iostream> using namespace std; int main() { int a,num; num=0; cout<<"Enter the number you want factorial of \n"; cin>>a; for(int x=a-1;x>0;x--) { num=a*x; cout<<x<<endl; } cout<<"Factorial is "<<num; return 0; } what's wrong here?

23rd Jun 2016, 7:40 AM
Divyanshu Bhatnagar
Divyanshu Bhatnagar - avatar
4 Respostas
+ 3
Hi! There is really big error. You will always get Factorial is {value of a(not value of num!!!)}. What is the cause? In your for-loop you update your num variable on each iteration. So in last iteration it looks like this: x=1; a=12; num = a*x;//you get 12 as a result What is the solution? You must save num variable. int main() { int a,num; num=1;//necessary to initialize multiplication with 1 cout<<"Enter the number you want factorial of \n"; cin>>a; for(int x=a-1;x>0;x--) { //we will increase this variable. Not update num* = x; cout<<x<<endl; } cout<<"Factorial is "<<num; return 0; }
23rd Jun 2016, 7:52 AM
Dmitry Pudov
Dmitry Pudov - avatar
0
Thank You very Much!! I got the issue. And for(int x=a... not x=a-1... ) Thank You very much. :))
23rd Jun 2016, 8:04 AM
Divyanshu Bhatnagar
Divyanshu Bhatnagar - avatar
0
You're welcome:)
23rd Jun 2016, 8:06 AM
Dmitry Pudov
Dmitry Pudov - avatar
0
fact=1 for(i=n;i>=1;i++) fact=fact×i
25th Jun 2016, 6:30 AM
Shubham Singh
Shubham Singh - avatar