两个两个地访问字符
Accesing the characters two by two
int getFirstValue(string number){
int result; //holds the converted value
int total = 0; //holds the sum
int count = 1;
// iterate through every character in the string
for (unsigned i = 0; i < number.length(); i++){
if (count % 2 == 0){
result = number[i] - '0'; //convert the character into an int
result *= 2; //multiply the value by 2
total += result; // assign it to total
++count; //increment count
}
}
return total; //return the sum
}
我想计算每两个数字乘以2的和。我不知道如何迭代一个数字,所以我选择把它作为一个字符串输入,然后转换数字。当我对每个数字进行尝试时,它工作得很好,但当我使用count变量时,它返回0。也许这是一个愚蠢的问题,但我想不出来。怎么了?
您的count
变量将只在if (count % 2 == 0)
语句结束时递增。由于count = 1
在循环之前,条件count % 2 == 0
将永远不会被验证,total
将一直保持0直到结束。
您应该在每次迭代中增加count
:
for (unsigned i = 0; i < number.length(); i++){
if (count % 2 == 0){
result = number[i] - '0'; //convert the character into an int
result *= 2; //multiply the value by 2
total += result; // assign it to total
}
++count; // HERE
}
请注意,count
将始终等于i+1
。
以下可能会有所帮助(我不确定您想要求和的数字,即单位,百,…)
int sum(int n)
{
int res = 0;
while (n != 0) {
res += n % 10;
n /= 100;
}
return 2 * res;
}
int sum(const std::string& n)
{
int res = 0;
for (std::size_t i = 0; i < n.size(); i += 2) {
res += *(n.rbegin() + i) - '0';
}
return 2 * res;
}
生活例子。
相关文章:
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 在函数中连接两个字符,并在 C++ 中返回输出
- 舍入 QDecDouble 值,精度最多为两个字符
- 计算两个字符序列
- 在c++中连接两个字符
- 有没有办法我可以从 istringstream 中读取两个字符
- 如何查看两个字符变量是否相等
- 使用位于 C 字符串中的两个字符*获取子字符串
- 比较两个字符的问题
- 如何修复密码条目,它一次输入两个字符
- 字符串构造函数将两个字符* 放入另一个 std::string 在 C++14 中有效,但不适用于 C++17
- 将两个字符数组相互添加
- 在 c++ 中添加两个字符
- 如何删除QString的前两个字符
- 如何使用两个字符来控制 C++ 程序的流程
- 如何将两个字符或字符串数组附加到一个数组中
- 如何从两个字符之间的文件中提取整数
- 删除两个字符之间的文本
- std::setw() 将特殊字符视为两个字符
- 比较两个字符*是否相等