c语言用递归法将一个整数n转换成字符串。例如输入483,应输出字符串“483”。n的位数不确定,可以是任意数位的正整数”
时间: 2024-05-11 16:18:49 浏览: 12
以下是用递归法将一个整数n转换成字符串的C语言代码实现:
```c
#include <stdio.h>
void int_to_str(int n, char str[])
{
if (n == 0) {
str[0] = '0';
str[1] = '\0';
return;
}
if (n < 0) {
str[0] = '-';
int_to_str(-n, str+1);
return;
}
int i = 0, temp = n;
while (temp > 0) {
temp /= 10;
i++;
}
str[i] = '\0';
while (n > 0) {
str[--i] = n % 10 + '0';
n /= 10;
}
}
int main()
{
int n = -483;
char str[20];
int_to_str(n, str);
printf("The string is %s\n", str);
return 0;
}
```
首先处理特殊情况,如果n为0,则直接将字符串设为“0”;如果n为负数,则在字符串首位加上符号“-”,并递归处理其绝对值。然后计算n的位数,并将字符串末尾设为NULL,最后按照从高位到低位的顺序将每一位数字转换成字符存储到字符串中。