在熟悉C ++的过程中,我正在重新研究一些初学者的算法。我已经不知道从哪里开始修复了一些错误。
1)以下是在fib()
函数返回其结果时出现的段错误。编辑:输入> = 9
#include <iostream>
using namespace std;
int fib(int n) {
int fibs[] = {1, 1}; // dynamic array
int i = 2; // start at 3rd element
while(i < n) {
fibs[i] = fibs[i-2] + fibs[i-1];
cout << "DEBUG: fibs[" << i << "] = " << fibs[i] << endl;
i = i+1;
}
cout << "about to return to main()" << endl;
return fibs[n-1];
}
int main() {
cout << "\n================= Hello cruel world =================" << endl;
cout << "Enter a number: ";
int x;
cin >> x;
cout << "fib(" << x << ") = " << fib(x) << endl;
cout << "================ Goodbye cruel world ================\n" << endl;
return 0;
}
否则,代码工作正常,可以正确找到数字。但是2)当我更改函数以支持长整数时,它开始表现得很奇怪:
#include <iostream>
using namespace std;
long fib(int n) {
long fibs[] = {1L, 1L}; // dynamic array
int i = 2; // start at 3rd element
while(i < n) {
fibs[i] = fibs[i-2] + fibs[i-1];
cout << "DEBUG: fibs[" << i << "] = " << fibs[i] << endl;
i = i+1;
}
cout << "about to return to main()" << endl;
return fibs[n-1];
}
int main() {
cout << "\n================= Hello cruel world =================" << endl;
cout << "Enter a number: ";
int x;
cin >> x;
cout << "fib(" << x << ") = " << fib(x) << endl;
cout << "================ Goodbye cruel world ================\n" << endl;
return 0;
}
输出:
================= Hello cruel world =================
Enter a number: 7
DEBUG: fibs[2] = 2
DEBUG: fibs[0] = 1
DEBUG: fibs[1] = 30071067265
DEBUG: fibs[2] = 30071067266
DEBUG: fibs[14] = 0
about to return to main()
fib(7) = 140733637791872
================ Goodbye cruel world ================
这对我来说没有任何意义。谢谢你的帮助。
最佳答案
int fibs[] = {1, 1};
等效于:
int fibs[2] = {1, 1};
换句话说,数组
fibs
(在两个程序中)只有两个元素,如果fibs[n]
大于n
,则访问1
是非法的。关于c++ - C++长整数奇数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20866205/