c语言小练

.编写一个函数实现n^k,使用递归实现
分析:n的k次=n*n*n*n*……*n(k个n),用递归的思想来讲,就等于n*(n的(k-1)次方)
#include <stdio.h>
#include <windows.h>
int fun(int n,int k)
{
    if(k==0)
        return 1;
    else if(k==1)
        return n;
    else
        return n*fun(n,k-1);
}
int main ()
{
    int n=0;
    int k=0;
    printf("求n的k次方\n");
    scanf("%d%d",&n,&k);
    printf("the namber is %d\n",fun(n,k));
    system("pause");
    return 0;
}
3. 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#include <stdio.h>
#include <windows.h>
int DigitSum(int n)
{
    if(n>9)
    {
        return     n%10+DigitSum(n/10);
    }
}
int main ()
{
    int n=0;
    printf("求输入n:\n");
    scanf("%d",&n);
    printf("the namber is %d\n",DigitSum(n));
    system("pause");
    return 0;
}
编写一个函数reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中
1.
#include <stdio.h>
#include <windows.h>
#include <assert.h>
void reverse_string(const char * const string)
{
    assert(string);
    if(*string=='\0')
    return ;
    reverse_string(string+1);
    putchar(*string);
}
int main (void)
{
    char string[80];
    gets(string);
    reverse_string(string);
    system("pause");
    return 0;
}
5.递归和非递归分别实现strlen
1.
#include <stdio.h>
#include <windows.h>
int  My_Strlen(const char *p)
{
   if(*p=='\0')
     return 0;
   else
     return 1+My_Strlen(p+1);
}
int main ()
{
    char *p="abcdef";
    int len=My_Strlen(p);
    printf("%d\n",len);
    system("pause");
    return 0;
}
2.#include <stdio.h>
#include <windows.h>
//.非递归实现strlen
int  My_Strlen(const char *p)
{
    int count=0;
    if(*p=='\0')
     return 0;
     else
    while(*p)
     {
         p++;
         count++;
     }
     return count;
}
int main ()
{
    char *p="abcdef";
    int len=My_Strlen(p);
    printf("%d\n",len);
    system("pause");
    return 0;
}

递归方式实现打印一个整数的每一位
#include <stdio.h>
#include <windows.h>
void fun(int n)
{
   if(n>9)
   {
       fun(n/10);
   }
   printf("%d\n",n%10);
}
int main ()
{
    int n=0;
    scanf("%d",&n);
   fun(n);
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lao_wine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值