为什么需要在索引上添加"0"以访问数组值?

编程入门 行业动态 更新时间:2024-10-23 04:39:41
本文介绍了为什么需要在索引上添加"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 )为了通过十进制代码将数字字符手动转换为整数,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'即可,而在另一个方向上,您可以将所有数字转换为通过添加'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"以访问数组值?

本文发布于:2023-11-29 16:42:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!