best-you-articles-040612

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;
}

分类:

技术点:

相关文章:

  • 2022-02-10
  • 2021-12-26
  • 2022-02-11
  • 2022-12-23
  • 2021-12-01
  • 2021-10-02
  • 2021-11-15
猜你喜欢
  • 2021-12-18
  • 2021-11-15
  • 2021-08-20
  • 2021-04-15
  • 2021-10-06
  • 2021-12-18
  • 2021-12-11
相关资源
相似解决方案