《C程序設計語言》第二版練習4-12參考程序

運用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';
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章