首页 > 解决方案 > 为什么我应该减去 '0' 以便我可以做 int_arr[5] = char_string[5]?

问题描述

所以我被分配用 c 语言存储两个 50 位整数并使用它们做数学方程式。我的问题是将输入的数字逐位存储在数组中。我想我可以将输入存储在一个 char 字符串中,如下所示:

#include <stdlib.h>
#include <stdio.h>

int main ()
{
    char string_test [50];
    scanf("%s", string_test);
    return 0;
}

但我不能将它用作数字,因为它存储为 char 并且我无法将它们逐位复制到另一个定义为 int 的数组中

经过一整天的搜索,我发现我需要像这样一个一个地复制我的字符串:

#include <stdlib.h>
#include <stdio.h>

int main ()
{
    char string_test [50];
    scanf("%s", string_test);

    int arr[50];

    for (int i = 0; i < 50; i++)
    {
        arr[i] = string_test[i] - '0';
    }
    return 0;
}

现在我的问题是为什么我需要减去“0”才能得到合适的结果?

标签: arraysccharinteger

解决方案


数字 0 - 9的ASCII值是:

Digit          0   1   2   3   4   5   6   7   8   9

ASCII value   48  49  50  51  52  53  54  55  56  57  

所以如果你有一个整数的字符串表示,比如说

char int_str[] = "123456";

并且需要将每个转换char为其数值,'0'从每个中减去 (48) 的值将导致值

int_str[0] == '1' ==>  '1' - '0' ==> 42 - 41 == 1
int_str[1] == '2' ==>  '2' - '0' ==> 43 - 41 == 2
int_str[2] == '3' ==>  '3' - '0' ==> 44 - 41 == 3
int_str[3] == '4' ==>  '4' - '0' ==> 45 - 41 == 4
int_str[4] == '5' ==>  '5' - '0' ==> 46 - 41 == 5
int_str[5] == '6' ==>  '6' - '0' ==> 47 - 41 == 6  

要将数字1 2 3 4 5 6转换为整数123456需要额外的步骤:

此示例使用封装在函数中的相同转换将离散char数字转换为int数字值,然后将每个离散 int 数字值同化为复合整数值:

int main(void)
{
    char str[] = "123456";
    int int_num = str2int(str);

    return 0;   
}

 int str2int(char *str)
 {
    int sum=0;

    while(*str != '\0')
    {    //qualify string
         if(*str < '0' || *str > '9')
         {
             printf("Unable to convert it into integer.\n");
             return 0;
         }
         else
         {   //assimilate digits into integer 
             sum = sum*10 + (*str - '0');
             str++;
         }
    }
    return sum;
}

推荐阅读