s [i]-'0'的使用 [英] Use of s[i] - '0'

查看:309
本文介绍了s [i]-'0'的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码基本上采用字符串并将其转换为整数值。我不明白为什么需要 int digit = s [i]-‘0’; 。为什么不能使用 int digit = s [i] 来工作? -'0'有什么用途?

The following code basically takes a string and converts it into an integer value. What I don't understand is why the int digit = s[i] - '0'; is necessary. Why can't it work by using int digit = s[i] instead? What purpose does the -'0' have?

int main(){

    string s = "123";
    int answer = 0;
    bool is_negative = false;
    if (s[0] == '-')
    {
        is_negative = true;
    }
    int result = 0;
    for (int i = s[0] == '-' ? 1 : 0; i < s.size(); ++i)
    {
        int digit = s[i] - '0';
        result = result * 10 + digit;
    }

    answer = is_negative ? -result : result;
    cout << answer << endl;
    system("pause");
}


推荐答案

首先,在您的问题标题中

Firstly, in your question title


使用'0'

the use of '0'

应写为


使用 s [i]-'0'

也就是说,通过减去 char 0的ASCII值(表示为'0'),我们得到<$以 char 格式表示的数字的c $ c> int 值(多数为ASCII值)。

That said, by subtracting the ASCII value of char 0 (represented as '0'), we get the int value of the digit represented in char format (ASCII value, mostly.)

这篇关于s [i]-'0'的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆