Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

fibonacci sequence overflow, C++

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...