C ++中的斐波那契数列不能超过47个数字 [英] Fibonacci series in C++ can't get more than 47 numbers
问题描述
我设计了这个程序,可以打印斐波那契数列( series [i] = series [i-1] + series [i-2]
),但我得到的数字不能超过47因为第48个数字变为负数和奇数(我认为这是在列表超出范围或该项为null时发生的情况):
I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]
) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
改进"的代码:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
推荐答案
当获得第47个值时,数字超出 int
范围. int
的最大值为 2,147,483,647
,第46个数字位于 1,836,311,903
的正下方.第47个数字超过了最大值, 2,971,215,073
.
When you get to the 47th value, the numbers go out of int
range. The maximum int
value is 2,147,483,647
and the 46th number is just below at 1,836,311,903
. The 47th number exceeds the maximum with 2,971,215,073
.
此外,正如LeonardBlunderbuss提到的那样,您使用的 for
循环超出了向量的范围.向量以 0
开头,因此通过具有 number< = length;
,将调用 range + 1
元素.范围只能达到 length-1
.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for
loop that you have. Vectors start with 0
, and so by having number<=length;
the range+1
element will be called. The range only goes up to length-1
.
这篇关于C ++中的斐波那契数列不能超过47个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!