Why if I did not assign zero for integer variables it may return wrong negative value?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<iostream>
#include<cmath>
usingnamespace std;
int main()
{
int n,i;
cout<<"please enter number"<<endl;
cin>>n;
cout<<"factorial of \t<<n<<"="<<endl;
int z;
int x=0;
for(i=n-1; i>0;i--)
{
z=n*i;
cout<<n<<"*"<<i<<"="<<z<<endl;
x=x+z; // I must give x zero in the declaration. Why?
}
cout<<"total is"<<x<<endl;
}
If you have int x;, it will not automatically given a proper value. It is not implicitly 0. It is undefined behavior to use a variable that isn't initialized.
Think of it another way: If you have A = <undetermined value> + B;, then what is the value of A? An undetermined value plus another value is still an undetermined value.
factorial grows very fast.
int, being 32 bits, is only 31 bits when signed. that is 2.1 billion. 12 is the largest you can compute before it overflows. When a signed number overflows, it turns negative, due to how 2's complement works; look that up if you do not understand what is happening.
put factorial down until the above makes sense. just play with an integer:
1 2 3 4 5 6 7 8
#include<iostream>
using std::cout;
int main()
{
char c = 127;
c += 1;
cout << (int)c << '\n'; //what do you get?! why?!
}
the above is what your problem probably is .... assuming your factorial is correct and you put in something too big to handle.