`
carolaif
  • 浏览: 70333 次
  • 性别: Icon_minigender_2
  • 来自: 大连
最近访客 更多访客>>
社区版块
存档分类
最新评论

C程序设计语言(第二版) 4-12

阅读更多

运用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;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics