CS50 pset 1-信用,更舒适

时间:2018-12-16 21:17:49

标签: cs50

我有以下错误 :(将5105105105105100标识为MASTERCARD     预期为“ MASTERCARD \ n”,而不是“ INVALID \ n” :(将4111111111111111标识为VISA     预期为“ VISA \ n”,而不是“ INVALID \ n” :(将4012888888881881标识为VISA

预期为“ VISA \ n”,而不是“ INVALID \ n”

但要使卡正确无误,最后一位数字应该正确(以我的情况而言)。请帮忙 -------------------代码-----------------------

#include <cs50.h>
#include <stdio.h>

int main()
{
    long long cardNumber;

// get a card number from the user
    do
    {
        printf("Your card number please: ");
        //scanf("%lld", &cardNumber);
        cardNumber = get_long_long();
    }
    while (cardNumber < 0);

//check the length of the card
    int counter = 0;
    long long cardNumberNeo = cardNumber;
    while (cardNumberNeo > 0)
    {
        cardNumberNeo = cardNumberNeo / 10;
        counter++;
    }

    if (counter != 15 && counter != 16 && counter != 13)
    {
        printf("INVALID\n");
    }

// Array of card number
    cardNumberNeo = cardNumber;
    int cardNumberArr[counter], cardNumberArrNeo[counter], i;
    for (i=0; i<counter; i++)
    {
        cardNumberArr[counter-i-1] = cardNumberNeo % 10;
        cardNumberArrNeo[counter-i-1] = cardNumberArr[counter-i-1];
        cardNumberNeo = cardNumberNeo / 10;
    }

    for (int i = 1; i < counter; i+=2)
    {
        cardNumberArrNeo[i] = cardNumberArrNeo[i] * 2;
    }

    int oddNumber = 0;
    int temp;

    for (int i = 0; i < counter; i++)
    {
        temp = (cardNumberArrNeo[i] % 10) + (cardNumberArrNeo[i]/10 % 10);
        oddNumber = oddNumber + temp;
    }

    if (oddNumber % 10 == 0)
    {
// Check the type of the card
        if ( ((cardNumberArr[0] == 3 && cardNumberArr[1] == 4) || (cardNumberArr[0] == 3 && cardNumberArr[1] == 7)) && counter == 15 )
        {
            printf("AMEX\n");
        }
        else if (cardNumberArr[0] == 5 && cardNumberArr[1] >= 1 && cardNumberArr[1] <= 5 && counter == 16)
        {
            printf("MASTERCARD\n");
        }
        else if (cardNumberArr[0] == 4 && (counter == 13 || counter == 16 ))
        {
            printf("VISA\n");
        }
        else
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

这将起作用.....只要信用卡号的长度为奇数。记住,Luhn的算法规则[加重]:

  

每隔两个数字乘以2,开头   倒数第二位,然后将这些产品的数字加在一起。

此循环for (int i = 1; i < counter; i+=2)处理长度相等的卡的错误数字。这样的数字需要从第0个索引开始,以便在正确的位置(即倒数第二个数字)结束。