运用printd函数的设计思想编写一个递归版本的itoa函数,即通过递归调用把整数转换为字符串
#include <stdlib.h> #include <stdio.h> /*思路:先调用itoa,在itoa中判断int型value是正还是负,无论正负,将value转换成unsigned型,然后调用utoa*/ char *utoa(unsigned value, char *digits, int base) { char *s, *p; s = "0123456789abcdef"; /* don't care if s is in * read-only memory */ if (base == 0) base = 10; if (digits == NULL || base < 2 || base > 36) return NULL; if (value < (unsigned) base) { digits[0] = s[value]; digits[1] = '\0'; } else { for (p = utoa(value / ((unsigned)base), digits, base); *p; p++); utoa( value % ((unsigned)base), p, base); } return digits; } char *itoa(int value, char *digits, int base) { char *d; unsigned u; /* assume unsigned is big enough to hold all the * unsigned values -x could possibly be -- don't * know how well this assumption holds on the * DeathStation 9000, so beware of nasal demons */ d = digits; if (base == 0) base = 10; if (digits == NULL || base < 2 || base > 36) return NULL; if (value < 0) { *d++ = '-'; u = -value; } else u = value; utoa(u, d, base); return digits; } int main(){ int num = 12; char* digits; digits = new char[10]; digits = itoa(num,digits,16); printf("%s\n",digits); return 0; }
下边是俺自己写的,见笑。
#include<stdio.h> void itoa(int n){ if(n<0) { putchar('-'); n=-n; } if(n/10) itoa(n/10); putchar(n%10+'0'); } int main(){ int n=12345; itoa(n); printf("\n"); return 0; }