用非递归的函数调用形式求斐波那契数列第n项

如题所述

#include <iostream>
using namespace std;
int main()
{
int n,a=1,b=2;
cout<<"Please input n:"<<endl;
cin>>n;
for(int i=0;i<n-1;i++)
{
a=b^a;
b=b+a^b;
a=a^a;
}
cout<<a<<endl;
return 0;
}
我所谓的斐波那契数列是1,2,3,5,8.。。。第一项是1的。
另外,^不是数学符号,不要include<cmath>.追问

^那这个是什么符号,这个没学过,有用temp做的么?

追答

是位运算的异或符号;
也可以用tmp做
同样的原理
我重新用tmp做吧
#include
using namespace std;
int main()
{
int n,a=1,b=2,tmp;
cout>n;
for(int i=0;i<n-1;i++)
{
tmp=a;
a=b;
b=b+tmp;
}
cout<<a<<endl;
return 0;
}

追问

include
int main()
{
int n;
long a=1,b=1,temp;
cout>n;
for(int i=3;i<=n;i++)
{temp=a+b;a=b;b=temp;}
cout<<b<<endl;
}

这个呢,对比一下

追答

感觉可以。
自己试一下,没有硬伤就应该是对的。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-13
main()
{
int n,n1;
n=scanf("%d",&n);/*输入要求的斐波那契数列的第n项的值*/
int a[1000];/*定义1000个元素的数组,存储斐波那契数列的前1000项*/
a[0]=1;a[1]=1;
for(n1=2;n1<1000;n1++){
a[n1]=a[n1-1]+a[n1-2];
}
printf(("%4d",a[n]);/*打印斐波那契数列的第n项的值*/

}本回答被网友采纳
第2个回答  2014-03-21
public class FibTest { public static void main(String[] arags){ long begin = System.currentTimeMillis(); System.out.println(fib(10)); long end = System.currentTimeMillis(); System.out.println(end - begin); } public static long fib(int n){ if(n < 3) return 1; else{ long a = 1; long b = 1; for(int i = 2 ; i < n-1 ;i++){ b = a + b; a = b - a; System.out.println("a = "+a +" b = "+b); } return a + b; } } }
相似回答