Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...