斐波那契序列溢出,C ++ [英] fibonacci sequence overflow, C++

查看:54
本文介绍了斐波那契序列溢出,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印斐波那契数列中的前100个数字.我的程序会打印直到大约20个数字,然后数字才变为负数.

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?

谢谢

/*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;
}

推荐答案

您看到的是一个整数溢出问题.firstNum和secondNum不长.

What you are seeing is an integer overflow problem. firstNum and secondNum are not long.

这应该解决

    unsigned long long i, fib;
    unsigned long long firstNum=0, secondNum=1;

这将帮助您避免20号之后的溢出,但是您的程序仍然会溢出.您可以使用unsigned long long,并将其设置为第100个序列元素.

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.

这篇关于斐波那契序列溢出,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆