Posted on 2012-08-12 09:58
hoshelly 閱讀(835)
評論(0) 編輯 收藏 引用 所屬分類:
Programming
編寫一遞歸函數將一根整數n轉換成字符串,例如輸入482,應輸出字符串“482”。n的位數不確定,可以是任意位數的整數。
代碼測試通過:
#include<stdio.h>
#include<string.h>
void IntToStr(int n);
char str[80]={0};
int main()
{
int num;
printf("input an integer number: ");
scanf("%d",&num);
IntToStr(num);
printf("The string is: %s\n",str);
return 0;
}
void IntToStr(int n)
{
int i;
if(n == 0)
return;
for(i=strlen(str)-1;i>=0;i--)
str[i+1]=str[i]; //向后移一位
str[0]=n%10+0x30; //最開始輸入的數字最后一位放在str[0],隨后向后移,直到n==0
IntToStr(n/10); //n不斷取除個位的其他高位數
}