检测有效的信用卡号算法

时间:2020-03-30 18:54:18

标签: c algorithm cs50 credit-card

我刚刚参加了在线CS50课程,并做了关于检测有效信用卡号的pset1。但是,我的算法无法正常运行。我使用调试工具来逐步查看结果,只要变量i从1到9都能正常运行,所有值都将正确添加到总和中。但是当涉及到i = 10时,依此类推,numNotSquared被分配为-8,numSquared被分配为-16,直到数字结束为止一直保持这种状态。请帮助我,谢谢。

// Headers and libraries
#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{
    // Prompt user for card number
    long cardNumber = get_long("Enter card number: ");

    // Get the length of input
    int length = floor(log10(cardNumber)) + 1;

    // Range validation
    if (length < 13 || length > 16)
    {
        printf("INVALID\n");
    }

    int numSquared = 0;
    int numNotSquared = 0;
    int sum = 0;

    // Algorithm to detect valid card
    // Based on Luhn's algorithm (https://lab.cs50.io/cs50/labs/2020/x/credit/)
    for (int i = 1; i <= length; i++)
    {
        // If digit is on odd position then mutiply by two
        if (i % 2 != 0)
        {
            {
                numSquared = ((int)(cardNumber / pow(10, length - i)) % 10) * 2;
            }
            // If the total is >= 10, then sum the products' digit
            if (numSquared >= 10)
            {
                sum += ((numSquared % 10) + 1);
            }
            else
            {
                sum += numSquared;
            }
        }
        // If digit is on even position then add to the sum
        else
        {
            numNotSquared = (int)(cardNumber / pow(10, length - i)) % 10;
            sum += numNotSquared;
        }
    }

    // Find remainder of (total / 10)
    if (sum % 10 == 0)
    {
        if (floor(cardNumber / pow(10, length - 1)) == 4)
        {
            printf("VISA\n");
        }
        else
        {
            int firstTwoDigits = floor(cardNumber / pow(10, length - 2));

            if (firstTwoDigits == 34 || firstTwoDigits == 37)
            {
                printf("AMEX\n");
            }
            else if (firstTwoDigits == 51 || firstTwoDigits == 52 || firstTwoDigits == 53 || firstTwoDigits == 54 || firstTwoDigits == 55)
            {
                printf("MASTERCARD\n");
            }
        }
    }
    else
    {
        printf("INVALID\n");
    }
}


0 个答案:

没有答案