Hi
while doing my homeworks, i stucked here ..
Writting a program to calculate the factorial of positive integer .
here is my code:

int main ()
{
	int x,factorial;
	cout<<"Enter an integer to calculate its factorial: ";
	cin>>x;
	if (x==1 && x==0)
	{
		cout<<"\nThe facotrial is: 1";
	}
	else
	{
		if (x<0)
	{
		cout<<"\nMath Error";
	}
	if (x>1)
	{
	cout<<"\nCalculating...";
	factorial = x;
	while (x>1)
	{
		factorial = factorial * ( factorial - 1 );
		x--;
	}
	}
	}
	cout<<"\nThe facotrial is: "<<factorial<<endl;
	return 0;
}

I know there is an arithmetic error ..
Thanks !

Have you learned for loops yet? That might be a better way about it:

My brain is kind of sleepy...is this right?

factorial = x;
for (i = x, while x is greater than 1, decrement x each iteration)
{
      factorial = factorial*(i-1);
}

I believe your error stems from the fact that you keep using the variable "factorial" in your loop but factorial is growing with each iteration.


factorial = factorial * ( factorial - 1 );

For example, 4! = 4*3*2*1 but your loop says 4! = 4 * (4-1) * ((4 *(4-1)-1)) *....and so on. Each time you are multiplying it by the product of the previous iteration less one.

These variables are uninitialized and could contain any value that happened to reside in their memory location at the time of their creation:

//These could be any value..!  we don't know what they are..!
int x,factorial;

How can x equal 1 and 0 at the same time?

if (x==1 && x==0)
//Should be
if (x==1 || x==0)

Try this:

factorial = x;
while (x > 1)	
{		
     factorial =* (x - 1);
     x--;
}

These variables are uninitialized and could contain any value that happened to reside in their memory location at the time of their creation:

//These could be any value..!  we don't know what they are..!
int x,factorial;

As far as good programming habits go, maybe those should be initialized. At the time those variables are used in this code they have known values in them.

Try this:
[...snip...]

Giving away code is not only against DaniWeb's policies, giving away code without an explanation of why it is done that way will not help the OP do anything other than pass his assignment.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.