为什么需要在索引中添加“0"才能访问数组值? [英] Why is there a need to add a '0' to indexes in order to access array values?

查看:26
本文介绍了为什么需要在索引中添加“0"才能访问数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这一行感到困惑:

sum += a[s[i] - '0']; 

为了给出一些上下文,这是代码的其余部分:

To give some context, this is the rest of the code:

#include <iostream>

using namespace std;

int main() {

    int a[5];
    for (int i = 1; i <= 4; i++)
        cin >> a[i];
    string s;
    cin >> s;
    int sum = 0;
    for (int i = 0; i < s.size(); i++)
        sum += a[s[i] - '0'];
    cout << sum << endl;
    return 0;
}

推荐答案

- '0' (或者移植性较差的- 48,对于ASCII only) 被使用为了通过十进制代码手动将数字字符转换为整数,C++(和 C)保证所有编码中的连续数字.

- '0' (or less portable - 48, for ASCII only) is used to manually convert numerical characters to integers through their decimal codes, C++ (and C) guarantees consecutive digits in all encodings.

例如,在 EBCDIC 中,代码范围从 <'0' 的 code>240 到 '9'249,这适用于 - '0',但会因 - 48 而失败).仅出于这个原因,最好始终像您一样使用 - '0' 表示法.

In EBCDIC, for example, the codes range from 240 for '0' to 249 for '9', this will work fine with - '0', but will fail with - 48). For this reason alone it's best to always use the - '0' notation like you do.

以 ASCII 为例,如果 '1' 的 ASCII 码是 49 并且 '0' 的 ASCII 码是 4849 - 48 = 1,或采用推荐的格式'1' - '0' = 1.

For an ASCII example, if '1''s ASCII code is 49 and '0''s ASCII code is 48, 49 - 48 = 1, or in the recommended format '1' - '0' = 1.

所以,正如您现在可能已经想到的那样,您可以使用这个简单的算术将字符中的所有 10 位数字转换为它是通过添加 '0' 进行字符编码.

So, as you probably figured out by now, you can convert all the 10 digits from characters using this simple arithmetic, just subtracting '0' and in the other direction you can convert all digits to it's character encoding by adding '0'.

除了代码中还有一些其他问题:

Beyond that there are some other issues in the code:

  • 数组不会在索引 0 处开始填充,而是在索引 1 处填充,因此,如果您的字符串输入是,例如,10"; sum 将是 a[1] + a[0],但 a[0] 没有赋值,所以 行为未定义,你需要观察适合这些情况.
  • The array does not start being populated at index 0, but at index 1, so if your string input is, for instance, "10" the sum will be a[1] + a[0], but a[0] has no assigned value, so the behaviour is undefined, you need to wach out for these cases.
for (int i = 0; i < 5; i ++)
    cin >> a[i];

会更合适,索引从04,因为数组有5个索引,如果你想输入1到5的数字,你可以减去1 稍后从 到索引.

would be more appropriate, indexes from 0 to 4, since the array has 5 indexes, if you want input numbers from 1 to 5, you can subract 1 from the to the index later on.

  • 正如评论部分所指出的,错误的输入(例如字母字符)也会引发未定义的行为.

这篇关于为什么需要在索引中添加“0"才能访问数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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