01.C语言总结将字符转化为数字
大家都知道字符对应相应的ascii码,那么如何用表示出字符本身的大小,而不表示出其所对应的ascii码
字符对应的ascii码的例子
#include<stdio.h>
int main()
{
char ch = 'a';
int a;
a = ch;
printf("%d", ch);
}
字符对应其本身大小
#include<stdio.h>
int main()
{
char ch[] = "1347857345";
char * temp = ch;
int a;
a = *temp - '0';
printf("%d", a);
}
小例题
不使用库函数,编写一个函数my_atoi(), 功能和atoi是一样的,
my_atoi(“+123”);结果为十进制123
提示:使用字符转化为整形
#include<stdio.h>
int my_atoi(char * str)
{
char *temp = str;
int flag = 0;
if(*temp == '-')
{
flag = 1;
temp = temp + 1;
}
else if (*temp == '+')
{
temp = temp + 1;
}
int num = 0;
while(*temp != '\0')
{
num = num * 10 + (*temp - '0');
temp ++;
}
if(0 == flag)
{
return num;
}
else
{
return -num;
}
}
int main()
{
printf("num1 = %d\n", my_atoi("+123"));
return 0;
}