+ 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?
4 ответов
+ 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;
}
0
Thank You very Much!! I got the issue. And for(int x=a... not x=a-1... )
Thank You very much. :))
0
You're welcome:)
0
fact=1
for(i=n;i>=1;i++)
fact=fact×i