01.C語言總結將字符轉化為數字


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM