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的总和。我不知道如何遍历数字,所以我选择将其作为字符串输入然后转换数字。当我尝试每一个数字它工作得很好,但当我使用计数变量它返回0.也许这是一个愚蠢的问题,但我无法弄清楚。怎么了?
答案 0 :(得分: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
。
答案 1 :(得分:0)
以下可能有所帮助(我不确定你要求哪些数字,例如,团结,数百......)
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;
}