关于斐波拉契数列打印问题
程序代码:
bool fibon_elem(int pos, int &elem); int main() { int pos; cout << "ein a position: "; cin >> pos; int elem; if(fibon_elem(pos, elem)) cout << "element # " << pos << " is " << elem << endl; else cout << "sorry, could not calculate element #" << pos << endl; return 0; } bool fibon_elem(int pos, int &elem) { if(pos <= 0 || pos > 1024) { elem = 0; return false; } elem = 1; int n_2 = 1, n_1 = 1; // n_2 = n_1; // n_1 = elem; for(int ix =3; ix <= pos; ++ix) { elem = n_2 + n_1; n_2 = n_1; n_1 = elem; } return true; }
代码时求斐波拉契数列的,输入一个位置,打印出相应的数值。疑问是在定义fibon函数时,为什么第二个形参使用了引用?
我直接使用了整形,打印的结果无论输入哪个位置,结果都是0.希望大神指点
[此贴子已经被作者于2017-3-10 14:06编辑过]