不知道那里出错了,请帮我改下
#include <string>
#include <iostream>
using namespace std;
bool fibon_elem(int pos,int &elem)
{
if(pos<=0 || pos>1024)
{
elem = 0;
return false;
}
else
{
int elem = 0;
int n_1 =1,n_2 = 1;
for(int ix = 3;ix <=pos; ++ix)
{
elem = n_1 + n_2 ;
n_2 = n_1;
n_1 = elem;
}
}
return true;
}
int main()
{
int pos;
cout<<"请输入一个位置"<<endl;
cin>>pos;
int elem;
if(fibon_elem(pos,elem))
{
cout<<"element #"<<pos<<"is"<<elem<<endl;
}
else
{
cout <<"sorry,coudl not#"<<pos<<endl;
}
return 0;
}
// 1,1,2,3,5,8,13,21,34,55,89,144 我就是想实现类似这种
比如我输入POS为12,就直接显示144
[解决办法]
你应该在fibon_elem函数的for循环中直接输出菲薄那次数列。
[解决办法]
去掉int elem = 0;
的int
[解决办法]
- C/C++ code
#include <string>#include <iostream>using namespace std;bool fibon_elem (int pos, int& elem){ if (pos <= 0 || pos > 1024) { elem = 0; return false; } else { elem = 0;//mark,int去掉,要不然变量被覆盖 int n_1 = 1, n_2 = 1; for (int ix = 3; ix <= pos; ++ix) { elem = n_1 + n_2 ; n_2 = n_1; n_1 = elem; } } return true;}int main(){ int pos; cout << "请输入一个位置" << endl; cin >> pos; int elem; if (fibon_elem (pos, elem)) { cout << "element #" << pos << "is" << elem << endl; } else { cout << "sorry,coudl not#" << pos << endl; } return 0;}