|
10鱼币
0. 你应该听说过 itoa 函数(函数文档 -> 传送门),它的作用是将一个整数转换成字符串形式存储。现在要求我们自己来实现一个类似功能的函数 myitoa(int num, char *str),该函数的第一个参数是待转换的整型变量,第二参数传入一个字符指针,用于存放转换后的字符串。- #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;
- }
- 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;
- }
复制代码
这道题看了答案还是不懂,求大佬注释一下
本帖最后由 bin554385863 于 2020-7-11 08:40 编辑
- #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;
- }
复制代码
|
|