《C程序设计语言》第二版练习4-12参考程序

本文介绍了一种使用递归方法实现的itoa函数,该函数能够将整数转换为字符串。通过递归调用自身处理整数的每一位,最终生成对应的字符串表示。文章包含了完整的C语言代码示例。

运用printd函数的设计思想编写一个递归版本的itoa函数,即通过递归调用把整数转换为字符串。

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
void itoa(int n, char s[]);
int main()
{
	int m;
	char s[SIZE];
	printf("Please enter a integer :\n");
	scanf("%d\n", &m);
	itoa(m,s);
	for (int i = 0; s[i] != '\0'; i++)
	{
		printf("%c", s[i]);
	}
	putchar('\n');
	system("pause");
	return 0;
}
void itoa(int n, char s[])
{
	static int i = 0;
	static int j = 0;
	if (n < 0)
	{
		n = -n;
		s[i++] = '-';
	}
	if (n / 10)
	{
		j++;
		itoa(n / 10, s);
	}
	j--;
	s[i++] = (n % 10 + '0');
	if (j < 0)
	{
		s[i] = '\0';
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值