此代码首先返回正确的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;
}
这就是它的回报:
如果有人能解释为什么这是请回答,我最近也开始学习C ++,所以请在评论中轻松一下:)
答案 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^9
,long long
左右大约,所以当数字超过时,它将为负数
如果您使用int
代替None
,您可以看到的数字范围变得更大