C++之函数的递归分析

本文介绍了递归函数的基本概念,并通过两个实例详细展示了递归函数的工作原理。第一个实例为计算阶乘的经典递归函数,第二个实例则展示了如何使用递归打印变量的地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

所谓递归,即函数在执行过程中调用自身(recursive)

最经典的,也是最简单的递归函数例子:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int factor(int n) {
    if(n==1)
        return 1;
    else
        return n*factor(n-1);
}
int main(int n) {
    printf("enter a n:\n");
    std::cin>>n;
    std::cout<<factor(n);
}
函数factor就是一个递归函数的例子,输出结果为n的阶乘。

这里,main函数放在factor之前就会报错。若想main放在factor之前,factor要先声明一下,即

int factor(int);

以下是代码原文

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int factor(int);
int main(int n) {
    printf("enter a n:\n");
    std::cin>>n;
    std::cout<<factor(n);
}

int factor(int n) {
    if(n==1)
        return 1;
    else
        return n*factor(n-1);
}

下面是另一个递归的example~,输出n所在的地址

#include <iostream>
#include <stdio.h>
void recursive(int);
int main(){
    recursive(1);
    
}
void recursive(int n){
    printf("Level %d: The address of n is %p \n",n,&n);
    if(n<4)
        recursive(n+1);
    printf("level %d: The address of n is %p \n",n,&n);\\ %p代表地址,对应&n
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值