写一个函数 int int_to _str(int n,chsr str[]); ,实现:把一个int型数据(由参数n表示)转换成一个字符串(放在str中),并返回整数的位数。
时间: 2024-03-10 18:50:12 浏览: 24
好的,以下是实现该函数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int int_to_str(int n, char str[]) {
int i = 0, sign = 0;
if (n < 0) {
sign = 1;
n = -n;
}
do {
str[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign) {
str[i++] = '-';
}
str[i] = '\0';
int len = i;
for (int j = 0; j < i / 2; j++) {
char temp = str[j];
str[j] = str[i - j - 1];
str[i - j - 1] = temp;
}
return len;
}
int main() {
int n = -123456;
char str[20];
int len = int_to_str(n, str);
printf("The integer is %d, the string is %s, the length is %d.\n", n, str, len);
return 0;
}
```
该函数将整数 n 转换成字符串并存储在 str 中,返回整数的位数 len。如果 n 是负数,先将其转换成正数并在字符串前面加上负号。实现过程中,使用 do-while 循环从低位到高位把每一位数字转换成字符存储在字符串中,最后反转字符串得到正确的顺序。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)