0

WHAT IS THE REASON THIS IS HAPPENNING!!!!

I was making a code to generate the fibbonachi number sequence, can somebody tell me whats wrong with my code, it works alright but then it randomly throws in a negative number -1323752223 Can you try In the Playground and see what's wrong with it!! Here it is: #include <iostream> using namespace std; int main() { int a=0,b=1,c; //declare Neccessary variables cout<<a<<endl; //Starting # 0 cout<<b<<endl; //Starting # 1 while(1){ c=a+b; // set c equal to sum of a and b (1+0=1) cout<<c<<endl; //print out sum(1) a=b; //set a equal to b in order to move on (a now = 1) b=c; //set b equal to the sum (c) to move on (b now = 1) // now repeat to get new sum (c) value } return 0; }

15th Dec 2016, 11:54 PM
Cybertheory
Cybertheory - avatar
1 Antwort
+ 6
Since the while runs forever, eventually, the variables are given values too high for them to contain. Add a condition to the while that can turn false before that happens. Make the variables long ints if you want higher values, too. The maximum value of an int is a bit more than 2.4 billion, I think. When you try to go higher, the variables wrap around into the negatives. The last bit of an int is meant to denote if its negative (1) or not (0), and it's being tripped when the number's get too high.
15th Dec 2016, 11:57 PM
Tamra
Tamra - avatar