递归与无递归实现斐波那契数列

本文展示了两种在C++中计算斐波那契数列的方法:一种是不使用递归的循环实现,从0和1开始,通过迭代计算后续项;另一种是采用递归,结合静态变量优化,避免重复计算。这两种方法分别给出了示例代码并展示了运行结果。
摘要由CSDN通过智能技术生成

不使用递归在C++中实现斐波那契数列。

#include <iostream>  
using namespace std;  
int main() {  
    int n1=0,n2=1,n3,i,number;    
    cout<<"Enter the numbers: ";    
    cin>>number;    
    cout<<n1<<" "<<n2<<" ";     
    for(i=2;i<number;++i) 
    {    
        n3=n1+n2;    
        cout<<n3<<" ";    
        n1=n2;    
        n2=n3;    
    }    
    return 0;  
}

得到结果 -
Enter the numbers: 7
0 1 1 2 3 5 8

在C++中使用递归实现斐波那契数列。

#include<iostream>    
using namespace std;      
void printFibonacci(int n){    
    static int n1=0, n2=1, n3;    
    if(n>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         cout<<n3<<" ";    
         printFibonacci(n-1);    
    }    
}    
int main(){    
    int n;    
    cout<<"Enter the numbers: ";    
    cin>>n;    
    cout<<"Fibonacci Series: ";    
    cout<<"0 "<<"1 ";  
    printFibonacci(n-2); d    
     return 0;  
}

结果 -
Enter the numbers: 8
Fibonacci Series: 0 1 1 2 3 5 8 13

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值