|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#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;
}
**** str[i++] = num / dec + '0'; 为什么每赋值后需要加一个'0'?
这是将数字转换为字符的必需,‘0’ 的 ASCII码是 48,‘9’ 的ASCII码是 57,
数字 0 + 字符 ‘0’ = 0 + 48 = 48 = 字符 ‘0’
数字 1 + 字符 ‘0’ = 1 + 48 = 49 = 字符 ‘1’
数字 2 + 字符 ‘0’ = 2 + 48 = 50 = 字符 ‘2’
数字 3 + 字符 ‘0’ = 3 + 48 = 51 = 字符 ‘3’
数字 4 + 字符 ‘0’ = 4 + 48 = 52 = 字符 ‘4’
数字 5 + 字符 ‘0’ = 5 + 48 = 53 = 字符 ‘5’
数字 6 + 字符 ‘0’ = 6 + 48 = 54 = 字符 ‘6’
数字 7 + 字符 ‘0’ = 7 + 48 = 55 = 字符 ‘7’
数字 8 + 字符 ‘0’ = 8 + 48 = 56 = 字符 ‘8’
数字 9 + 字符 ‘0’ = 9 + 48 = 57 = 字符 ‘9’
|
|