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

查看:94
本文介绍了为什么需要在索引上添加"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 ,用于

- '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代码为 48 49-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'即可,而在另一个方向上,您可以将所有数字转换为通过添加'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];

更合适,索引从 0 4 ,因为数组有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天全站免登陆