When running the following code I end up getting negative values. I am only using positive numbers so I am really confused. I have tried to see if this negative number was a return code but there dose not seem to be any codes that return this as a number.
public static int fib(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return b;
}
static void Main(string[] args)
{
int n = 0;
bool Run = true;
while (Run == true)
{
n = fib(n + 1);
Console.WriteLine(n);
}
}
Here are the results when the code is run:
1
2
3
5
13
610
-121099088
1
You’re just seeing integer overflow. You’re trying to compute
fib(610)which is way more than anInt32can hold – and when you add two large integers together, you’ll get a negative number.If you build it in “checked” mode, an exception will be thrown instead – or you can do it just for the one expression you need:
See MSDN for more on checked arithmetic.