zoukankan      html  css  js  c++  java
  • TCPL学习笔记:4-12以及4-13。关于使用递归的问题。

    4-12.写一个函数itoa,通过递归调用将整数转换成为字符串。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 void Itoa(int num, char * s);
     4 int main(void)
     5 {
     6     char s[20];
     7     Itoa(1234567, s);
     8     printf("The str now is %s", s);
     9     return 0;
    10 }
    11 
    12 void Itoa(int n, char * s)
    13 {
    14     static int i = 0;
    15     if(n < 0)
    16     {
    17         s[i++] = '-';
    18         s[i] = '';
    19         n = -n;
    20     }
    21     else
    22     {
    23         if(n/10)
    24             Itoa(n/10, s);
    25         s[i++] = '0' + n%10;
    26         s[i] = '';
    27     }
    28 
    29 }

    编译结果为:The str now is 1234567
    Process returned 0 (0x0)   execution time : 0.029 s
    Press any key to continue.

    4-13.编写一个递归版本的reverse(s)函数,用于将字符串s倒置。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 void reversed(char * s, char * d);
     4 int main(void)
     5 {
     6     char s1[20] = "wangcheng";
     7     char s2[20];
     8     reversed(s1, s2);
     9     printf("The reversed string is : %s", s2);
    10     return 0;
    11 }
    12 
    13 void reversed(char * s, char * d)
    14 {
    15     static int i = 0;
    16     static int j = 0;
    17     if(s[i+1] != '')
    18     {
    19         i++;
    20         reversed(s, d);
    21     }
    22          d[j++] = s[i--];
    23          d[j] = '';
    24 }
    1 编译运行结果为:The reversed string is : gnehcgnaw
    2 Process returned 0 (0x0) &nbsp; execution time : 0.009 s
    3 Press any key to continue.
  • 相关阅读:
    SQL Serever学习16——索引,触发器,数据库维护
    微信WeUI基础
    SQL Serever学习15——进阶
    SQL Serever学习14——存储过程和触发器
    微信WeUI入门2
    微信WeUI入门
    数据库—索引
    数据库—四种存储引擎
    视图
    事务
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4874257.html
Copyright © 2011-2022 走看看