首页 > 解决方案 > 检测有效信用卡号算法

问题描述

我刚刚注册了在线 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");
    }
}


标签: calgorithmcs50credit-card

解决方案


推荐阅读