Reputation: 95
Edited: pasted the correct code this time...
I'm trying to calculate a factorial of a number. In this example, I enter the number 5.
Trying this method, gives me a huge negative number:
static void Main(string[] args)
{
int consoleInput = int.Parse(Console.ReadLine());
for (int i = 1; i < consoleInput; i++)
{
consoleInput = consoleInput * i;
}
Console.WriteLine(consoleInput);
}
Outputs -1899959296
However:
static void Main(string[] args)
{
int consoleInput = int.Parse(Console.ReadLine());
int result = consoleInput;
for (int i = 1; i < consoleInput; i++)
{
result = result * i;
}
Console.WriteLine(result);
}
Outputs 120
If I enter 5 both times, the first time the output is -1899959296 and the second time, the output is 120.
Can someone explain why?
Upvotes: 1
Views: 540
Reputation: 10929
The problem is you change 'consoleInput
' in each loop:
for (int i = 1; i < consoleInput; i++)
{
consoleInput = consoleInput * i;
}
Now the 'for
' checks against a new value every time.
The reason it gets negative is an overflow condition.
Edit:
The reason it gets so large, is because the loop 'never' ends, since the value you check against grows on every loop.
Upvotes: 5