第05天C语言(09):递归-练习1

一、概念
二、代码
#include <stdio.h>

int myPow(int base,int n);
int myPow2(int base,int n);
int main()
{
#pragma 1.涉及一个函数 用来计算B的n的次方
    /*
     b = 2
     n = 3
     
     int result = b(3);
     
     b(0) = 1;
     b(1) = b;      == b(0) * b
     b(2) = b * b;   == b(1) * b
     b(3) = b * b * b; == b(2) * b
     b(n) = b(n -1) * b
     
     2(3)
     2 * 2 * 2;
     result = 1 * 2
     result = 2(result) * 2;
     result = 2 * 2(result) * 2;
     
     用上一次的结果 * 2
     */
    
    int a = 2;
    int b = 3;
//    int result = myPow(a,b);
    int result = myPow2(a, b);
    printf("result = %i\n",result);
    
    
    
    
    return 0;
}

#pragma mark for循环
int myPow(int base,int n)
{
    // 1.定义变量保存计算结果
    int result = 1;
    for (int i = 0; i < n; i++) {
        printf("%i * %i\n",result,base);
        result = result * base;
    }
    return result;
}
#pragma mark 递归
/*
 1.必须有一个明确的结束标志
 2.自己调用自己
 */
int myPow2(int base,int n)
{
    int result = 1;
    if (n <= 0) {
        // 结束条件
        return result;
    }
    else
    {
       return  myPow2(base, n - 1) * base;
    }
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容