|
发表于 2020-10-11 08:39:34
|
显示全部楼层
先看程序,有注释,若还不明白,提出来
- #include <stdio.h>
- char *myitoa(int num, char *str);
- char *myitoa(int num, char *str)
- {
- int dec = 1;
- //保存数字的权值
- int i = 0;
- //字符数组的索引
- int temp;
- //临时过渡
- if (num < 0)
- {
- str[i++] = '-';
- num = -num;
- //如果数字是负数,将字符数组的首字符填充为负号,并把数字转化为正值
- }
- temp = num;
- while (temp > 9)
- {
- dec *= 10;
- temp /= 10;
- //如果temp大于10,判断数字的位数
- }
- while (dec != 0)
- {
- str[i++] = num / dec + '0';
- num = num % dec;
- dec /= 10;
- //循环迭代拆分数字,并转化为字符填充字符数组
- }
- str[i] = '\0';
- //添加字符数组结束符
- return str;
- //返回字符数组的指针
- }
- int main(void)
- {
- char str[10];
- printf("%s\n", myitoa(520, str));
- printf("%s\n", myitoa(-1234, str));
- return 0;
- }
复制代码 |
|