为什么需要在索引中添加“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 码是 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'
进行字符编码.
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 index1
, so if your string input is, for instance,"10"
thesum
will bea[1]
+a[0]
, buta[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.
- 正如评论部分所指出的,错误的输入(例如字母字符)也会引发未定义的行为.
相关文章