C++ 卡验证问题

C++ card validation issue

我是一个编码菜鸟,我正在尝试使用一个简单的 Luhn 算法来进行信用卡验证检查。我已经走到这一步了,我不太明白我这样做的方式有什么问题,但答案总是正确的。

如果有人能提供帮助,我将不胜感激。

#include <iostream>
#include <cstring>
using namespace std;

bool validate(char card_number[]);

int main(int argc, char *argv[])
{
   cout << validate(argv[1]) << endl;
   return 0;
}

bool validate(char card_number[])
{
   bool valid = false;
   int length = 0;
   int step_1 = 0;
   int step_2 = 0;
   int result = 0;

   while (card_number[length] != '[=10=]') {
       length++;
   }


   for (int i = card_number[0]; i < card_number[length]; i++) {

       if (( i % 2 != 0 && i != 0)) {

           int temp = card_number[i] - '0';

           if((temp / 10) >= 1) {
               step_1 = step_1 + (temp / 10) + (temp % 10);
           } else {

               step_1 = step_1 + temp;             
           }
       } else {

           step_2 = step_2 + card_number[i] - '0';         
       }
   }
   result = step_1 + step_2;

   if (result % 10 == 0) {
       valid = true;
   }

   return valid;
}

正如其他人在评论中所说,您必须遍历数组索引,而不是数组元素。

此外,根据 Luhn 的算法,您的条件 if((temp / 10) >= 1) 是错误的(永远不会满足),因为 temp 是一个数字,它永远不会大于 9。您要做的是验证数字的两倍 (temp) 是否大于或等于 10 .

要实施 Luhn 算法(至少是 this Wikipedia page 中描述的算法),您应该遍历卡号的每个数字并应用一些转换。

计算完数字的长度后,贴出的代码中的循环如下所示

for (int i = card_number[0]; i < card_number[length]; i++) { // ...
//           ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^

其中card_number是命令行输入的以null结尾的char数组,所以前者相当于

for (int i = '7'; i < 0; i++) { // ...
//           ^^^      ^  Note that any "digit" would have a value greater than 0   

这个循环将被跳过,result 将始终保持等于 0。

其余代码似乎部分或不符合算法(如果我链接的代码是 OP 实际需要的代码)。这是一个可能的实现。

if (length == 0)
    return false;

int sum = 0;
// Loop over the array from the beginning (the "left" side of the number)
for (int i = 0; i < length - 1; ++i)
{
    int digit = card_number[i] - '0';

    // Now determine if this is an odd or even position, but from the
    // "right" side of the number
    if ( (length - 1 - i) % 2 )
    {
        // You missed this part, according to https://en.wikipedia.org/wiki/Luhn_algorithm
        digit *= 2;

        // If it's not a single digit anymore...
        if ( digit > 9 )
        {
            // Reduce to one digit again
            digit -= 9;               
        }
    }

    sum += digit;
}

// You missed this part too, always according to Wikipedia
if ( (sum * 9) % 10  !=  card_number[length - 1] - '0') {
    return false;
}

return true;