c++ - 添加该行的所有总和
问题描述
我想在 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。我打印了每个字符和总数,以便更容易看到发生了什么。
解决方案
您正在对字符代码求和,而不是文字数字。请参阅 ASCII 表。
ASCII 代码:
'1'
是 49'3'
是 51'0'
是 48'2'
是 50
因此你得到 49 + 51 + 48 + 48 + 51 + 50 + 49 即 346。
推荐阅读
- python - 5x5 滑动拼图快速和低移动解决方案
- c# - 带有过滤器的 C# 中的 MongoDB Linq 查询
- node.js - node.js 无头浏览器仅访问 javascript 全局变量
- java - XPathFactory#newInstance() 未能为默认对象模型创建 XPathFactory:http://java.sun.com/jaxp/xpath/dom
- image - Xamarin:从 url 列表到使用图像填充 CollectionView
- node.js - TypeScript,Apollo GraphQL 产生不可分配的节点获取错误
- laravel - 避免 SESSION_DOMAIN 应用于 Laravel 中的子域
- python - 将字典变量放入列表 - 打乱它们 - 将它们分成两个嵌套的字典
- python - 使用 Pandas 熔化
- javascript - 滚动到顶部时,ScrollTop 不会恢复