两个两个地访问字符

Accesing the characters two by two

本文关键字:两个 字符 访问      更新时间:2023-10-16
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;
}

生活例子。