正如标题所说,我试图找到输入函数的数字中每隔两个数字的数字总和。第一个数字将是倒数第二个数字。例如,输入 58423 应返回 2*2 (4), 8*2 (16-> 1+6 = 7) -->4+7 = 11。我的根本不是这样工作的,似乎返回随机数字。函数如下。
我使用的事实是,n % 10 将为您提供 n 的最右边的数字,而 (n/10) % 10 将为您提供 n 的下一个最右边的数字,依此类推,其中 n 是输入的数字。
int everyOther(long num) //(n / 10) % 10 will get you the next rightmost
digit
{
int incrementer = 1;
int total = 0;
long shifter = 1;
int a = 0;
while(true)
{
shifter = shifter *100;
if(num/shifter == 0)
{
break; // will have reached the end of the number if this is
//true
}
a = 2* ((num / shifter) % 10); // every other digit right to left
//starting from the second to last, multiplied by two
total = total + (a/10 + a%10); //sum of the above product's
//digits
incrementer++;
}
return total;
}
最佳答案
您有两个错误。
首先,每个循环只需执行一次 shifter = 100 * shifter;
。在每次迭代中,您希望 shifter
是前一次迭代的 100 倍。所以只需乘以 100 一次即可。您可以摆脱incrementer
。这是多余的。
其次,您的示例显示将 16 的数字相加得到 7。但由于某种原因,您注释掉了执行此操作的代码。
int everyOther (long num)
{
int shifter = 1; // dividing by 10 gets us the hundreds digit
int total = 0;
int a = 0;
while (num/shifter > 0)
{
shifter *= 100; // move two digits over
if(num/shifter == 0)
{
break;
}
a = 2 * ((num / shifter) % 10);
total += (a/10 + a%10);
}
return total;
}
关于c - 我的求输入的每个其他数字的两倍的数字之和的函数在 C 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56728736/