描述
编写函数,函数功能:把一个整数转换为一个数字字符串。
#include <stdio.h>
int main(){
int n;
char a[16];//16个能满足吗?
void ConvertIToA(int n,char a[ ]);
scanf("%d",&n);
ConvertIToA(n,a);
printf("%s",a);
return 0;
}
//以下声明函数
输入
输入一个整数n。-10000<=n<=10000.
输出
输出这个数的字符串,如果是正整数,正号不需要输出。
样例输入
123
样例输出
123
代码:
void ConvertIToA(int n,char a[])
{
int i,j=0;
if(n<0)
{
putchar('-');//向终端输出-
n=-n;
}//将负数变为正数
if((i=n/10)!=0)
{
j++;
ConvertIToA(i,a);
}//得到字符串长度
a[j]='\0'; //在字符串末尾加上‘\0’
putchar(n%10+'0');//转化为字符串
}
123/10=12 继续递归
12/10=1 继续递归
1/10=0 结束递归
继续
1%10=1 变为’1’回到上一层
12%10=2 变为’2’回到上一层
123%10=3 变为’3’