为什么这个C ++ fibonacci序列程序适用于前46个术语,但之后开始给出看似随机的数字?

时间:2017-01-10 19:14:34

标签: c++ fibonacci

此代码首先返回正确的Fibonacci术语,但是当它到达第47个术语时,它开始给出负数或看似随机的数字

这是我的代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

int main() {
    int x;
    int t1 = 0;
    int t2 = 1;
    int nextTerm = 0;
    cout<< "Enter the term in the sequence that you want:\n";
    cin>> x;

    for (int i = 1; i <= x; i++) {
        if (i == 1) {
            cout<< t1 << ", ";
            continue;
        }

        if (i == 2) {
            cout<< t2 << ", ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;

        cout<< nextTerm << ", ";

    }
    cout<< "\n";
    return 0;
}

这就是它的回报:

enter image description here

如果有人能解释为什么这是请回答,我最近也开始学习C ++,所以请在评论中轻松一下:)

3 个答案:

答案 0 :(得分:2)

c ++中的内置数字类型具有可以表示的固定值范围。当int等有符号整数超出此范围(oveflow)时,会发生什么情况。通常你会注意到它们包含在那里尽可能小的可表示值,但不要指望它。有关详细信息,请参阅std::numeric_limits。请注意,值的范围取决于您的平台和编译器。

cstdint标头中定义的类型intmax_t将为您提供平台的最大整数类型。

答案 1 :(得分:1)

你检查过你的整数有多大吗? c ++ int只能保存一定大小的整数,当你向它添加更多时,它会溢出(模拟算法就像模拟时钟一样:如果它是10点,你等待4个小时就是2点钟)。所以一个非常大的数字+东西=非常小的数字(通常)。

F_47 = 2971215073

检查出来:How would you set a variable to the largest number possible in C?

答案 2 :(得分:0)

只有2^31-1的数字小于或等于10^9long long左右大约,所以当数字超过时,它将为负数 如果您使用int代替None,您可以看到的数字范围变得更大