简体   繁体   English

C 中的 Luhn 算法

[英]Luhn Algorithm in C

I'm very new to coding and one of the assignment is to program Luhn's Algorithm.我对编码很陌生,其中一项任务是编写 Luhn 算法。 After searching on the internet, everyone's solution looks so different and foreign:( so I don't know where the problem is with my solution. Any help is appreciated!在互联网上搜索后,每个人的解决方案看起来都如此不同和陌生:(所以我不知道我的解决方案问题出在哪里。感谢任何帮助!

int main(void)
{
    // get card number from user
    long number;
    do
    {
        number = get_long("Number: ");
    } while (number < 0);

    // isolate digits of card number
    int digit;
    int product;
    int sum;
    int totalSum;
    int counter;
    for (counter = 1; number > 9; counter++) {
        for (int i = 1; number > 9; i = i * -1) {
            digit = number % 10;

            // isolate digits that need to be multiplied by 2
            if (i == 1) {
                product = digit * 2;

                // add products' digits
                if (product > 9) {
                    sum = (product % 10) + 1;
                }
            }
            // add sum of digits that weren't multiplied by 2
            totalSum = product + sum + digit;

            // update "new" number
            number = (number - digit) / 10;
        }
    }

    // checksum
    int check = totalSum % 10;
    if (check != 0) {
        printf("INVALID\n");
    } else {
        printf("VALID\n");
    }
}

There are a number of errors in your code, most having to do with how you use variables.您的代码中有许多错误,大多数与您使用变量的方式有关。

  1. You use totalSum without ever initializing it, which means it can start with any random value!您使用totalSum时从未初始化它,这意味着它可以从任何随机值开始!

  2. You add both product and sum to totalSum every time, but you only update their values when some condition applies.您每次都将productsum添加到totalSum中,但仅在某些条件适用时才更新它们的值。
    This means at least half the time (maybe more) you add old values you already added previously.这意味着至少有一半的时间(也许更多)您添加之前已经添加的旧值。

  3. Your loops exit when number is 9 or less, meaning you never check the leftmost (highest) digit of number.number为 9 或更少时,您的循环退出,这意味着您永远不会检查 number 的最左边(最高)数字。

As the comments suggested, you should read the pseudo code in Wikipedia , look carefully what they put in each variable, and what they sum and multiply.正如评论所建议的,您应该阅读Wikipedia 中的伪代码,仔细查看它们在每个变量中放入的内容,以及它们相加和相乘的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM