问题
I want to print the first 100 numbers in the fibonacci sequence. My program prints until around 20 numbers than the numbers turn negative.
Can someone explain this to me please and provide a fix?
Thanks,
/*Fibonacci sequence*/
#include <iostream>
using namespace std;
int main(){
long int i, fib;
int firstNum=0, secondNum=1;
cout << firstNum << endl;
cout << secondNum << endl;
for (i=0; i < 100; i++){
fib = firstNum + secondNum;
firstNum = secondNum;
secondNum = fib;
cout << fib << endl;
}
return 0;
}
回答1:
What you are seeing is an integer overflow problem. firstNum and secondNum are not long.
This should fix it
unsigned long long i, fib;
unsigned long long firstNum=0, secondNum=1;
EDIT:
This will help you avoid overflow after the 20th number, but your program will still overflow. You can use unsigned long long, and you'll make it to the 100th sequence element.
回答2:
Well even unsigned long long int throws out of range for higher fabonacci num(above 92) but if still interested you could store them digit by digit in array
see this https://docs.google.com/file/d/0BwtP9e5j1RbpSjhvSG4wbkhGcmM/edit
回答3:
- Either We can store the values in dynamically created structures such as Linked list (If we want to store all the Fibonacci numbers) OR
- We can use just three string arrays to hold the sum and temp values to print it for this purpose which will solve your issue.
Please see this for reference
Print nth Fibonacci number [upto 1000 digits]
来源:https://stackoverflow.com/questions/33179674/fibonacci-sequence-overflow-c