Определить действительный алгоритм номера кредитной карты - PullRequest
0 голосов
/ 30 марта 2020

Я только что записался на онлайн-курс CS50 и выполняю pset1 для определения действительного номера кредитной карты. Однако мой алгоритм работает не так, как я ожидал. Я использовал инструмент отладки, чтобы увидеть пошаговый результат, поскольку переменная, которую я запускаю от 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");
    }
}


...