标签:
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] = ‘\0‘; 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] = ‘\0‘; 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] != ‘\0‘) 18 { 19 i++; 20 reversed(s, d); 21 } 22 d[j++] = s[i--]; 23 d[j] = ‘\0‘; 24 }
1 编译运行结果为:The reversed string is : gnehcgnaw 2 Process returned 0 (0x0) execution time : 0.009 s 3 Press any key to continue.
TCPL学习笔记:4-12以及4-13。关于使用递归的问题。
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4874257.html