尝试用 C 语言实现 Luhn 算法,但没有得到每隔一个数字的预期总和



我正在尝试实现Luhn的算法。对于每一个其他数字,你必须将其乘以2,然后将其添加到一个连续的总数中。如果第i个数字*2大于10,则将其拆分,然后将其添加到运行总数中。我创建了一个void函数来执行此操作,并将123456789作为测试值传递。

#include <stdio.h>
// #include <cs50.h> // 
void LuhnsAlgorithm(long); // needs to be changed to str return type when submitted
int main()
{

int num = 123456789;
LuhnsAlgorithm(num);
}
void LuhnsAlgorithm(long cc) // return type will be str when submitting
{
int sum = 0;
// case 1
// case 2 (every other odd digit, multiplied by 2, and then added)
long case2 = cc;
while (case2 > 0)
{
if ((case2 / 10 % 10) * 2 >= 10) // checks if the every-other-digit's product when multiplied by 2 is bigger than 10 (aka, has 2 digits)
{
// creating this stupid temp variable 
int digitBreakUp = case2 / 10 % 10 * 2;
sum += (digitBreakUp / 10) + (digitBreakUp % 10);
}
else // if the product is just 1 digit then add it to the sum
{
sum += (case2 / 10 % 10) * 2;
}
case2 = case2 / 10;
}
printf("The sum of every last other digit in 123456789 is %in", sum);
}

期望的总和为22(8->1+6,6->1+1,4->8,2->4(。但是,我36岁了。怎么了?我如何达到0/使其达到"停止迭代">,直到它达到数字的开头?

感谢

由于您的测试是针对每隔一个数字的,因此代码行:

case2 = case2 / 10;

应为:

case2 = case2 / 100;

如果你这样做,你的每一个数字的总和就会变成22。

试试看。

最新更新