我在用C实现Luhn算法时遇到问题吗?

时间:2019-06-21 00:14:14

标签: c luhn

到目前为止,我仅在第一部分中工作,您必须将数字中从第二个数字到最后一个数字的其他数字乘以2,然后将其数字相加。由于2个错误,我无法通过此操作。有一段时间,while循环似乎永远不会结束,这会导致移位变得太大而导致溢出错误。但是同时,我得到了行除以零的误差:a = num%shift; ?不确定当偏移量太大时怎么可能,它怎么可能变成零?

bool luhnCheck(long num)
{
    int a = 2;
    int b;
    int total = 0;
    int incrementer = 0;
    long shift = 1;
    while(a != 0)
    {
        incrementer++;
        for(int i = 1; i<=incrementer; i++)
        {
            shift *= 100;
        }
        a = num % shift;
        b = a/(shift/10); //- a % (shift/10); // every other digit starting from the second to last one
        if(a!= 0)
        {
            total+= ((2*b) % 10) - ((2*b)/10); //sum of digits
        } 

    }    

    return total;

}

0 个答案:

没有答案
相关问题