我想在 get_line_sum 函数中获取字符串中每个字符的总和(例如:“1300321”将返回 10)。但是,我的总和似乎与我想得到的不匹配。
#include <iostream>
#include <string>
int get_line_sum(std::string x) {
int total = 0;
for (char &c : x) total += c;
return total;
}
int main() {
std::cout << get_line_sum("1300321") << std::endl;
}
c: 1 total: 0
c: 3 total: 49
c: 0 total: 100
c: 0 total: 148
c: 3 total: 196
c: 2 total: 247
c: 1 total: 297
346
输出是 346,而不是 10。我打印了每个字符和总数,以便更容易看到发生了什么。
最佳答案
您是在对字符代码求和,而不是对文字数字求和。 See the ASCII table .
ASCII 码:
'1'
是 49'3'
是 51'0'
是 48'2'
是 50
因此你得到 49 + 51 + 48 + 48 + 51 + 50 + 49 即 346。
关于c++ - 添加该行的所有总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245078/