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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值