|
5鱼币
本帖最后由 Justin1 于 2020-5-6 18:44 编辑
这是这个题目
你应该听说过 itoa 函数(函数文档 -> 传送门),它的作用是将一个整数转换成字符串形式存储。现在要求我们自己来实现一个类似功能的函数 myitoa(int num, char *str),该函数的第一个参数是待转换的整型变量,第二参数传入一个字符指针,用于存放转换后的字符串
我自己写了一套代码,模仿甲鱼的,感觉实际上意思差不多,但是我的第二个while循环出了问题。
小甲鱼的代码这两句句的
+'0'不大理解 str[i++] = num / (int)(pow(10,len)) + '0';
str[i] = '\0';
这个是我写的】
- /******************************************************************************
- Online C Compiler.
- Code, Compile, Run and Debug C program online.
- Write your code in this editor and press "Run" button to compile and execute it.
- *******************************************************************************/
- #include <stdio.h>
- #include <math.h>
- char myitoa(int num, char *str);
- char myitoa(int num, char *str)
- {
- int i = 0;
- int j = 0;
- int len;
- int temp;
-
- if(num < 0)
- {
- str[i++] = '-';
- num = -num;
- }
-
- do
- {
- temp = (int) pow(10,++j);
- }
- while(temp < num);
-
- len = j -1;
- while( pow(10,len) != 1)
- {
- str[i++] = num / (int)(pow(10,len)) + '0';
- num = num % (int)(pow(10,len));
- len = len -1;
- if( len == 0)
- {
- str[i++] = num;
- }
- }
-
- str[i] = '\0';
- return str;
-
- }
- int main()
- {
- char str[10];
- printf("%s\n",myitoa(520, str));
- //printf("%s\n",myitoa(-1234, str));
-
- return 0;
- }
复制代码
这个是甲鱼的
- #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;
- }
复制代码
if( len == 0)
{
str[i++] = num + '0'; //这行添加 + '0'
}
+'0'的作用是将数字转换为对应的ASCII码,比如某一位的数字是5,将这个整数的5加上'0'的ASCII码48得到53,就是'5'的ASCII码。
str[ i ] = '\0';是给得到的字符串添加一个结束标志。
另外,你的 char myitoa(int num, char *str),返回值应该是char *吧
|
最佳答案
查看完整内容
if( len == 0)
{
str = num + '0'; //这行添加 + '0'
}
+'0'的作用是将数字转换为对应的ASCII码,比如某一位的数字是5,将这个整数的5加上'0'的ASCII码48得到53,就是'5'的ASCII码。
str[ i ] = '\0';是给得到的字符串添加一个结束标志。
另外,你的 char myitoa(int num, char *str),返回值应该是char *吧
|