首页 > 解决方案 > 添加该行的所有总和

问题描述

我想在 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。我打印了每个字符和总数,以便更容易看到发生了什么。

标签: c++stringc++17

解决方案


您正在对字符代码求和,而不是文字数字。请参阅 ASCII 表

ASCII 代码:

  • '1'是 49
  • '3'是 51
  • '0'是 48
  • '2'是 50

因此你得到 49 + 51 + 48 + 48 + 51 + 50 + 49 即 346。


推荐阅读