0

我已经编写了Luhn 算法的实现。当我使用按位数无效的数字测试程序时,我没有收到程序错误。相反,程序printf()在 main 函数中执行调用。但是,每当我按照算法使用有效卡号测试程序时,我都会得到除以 0 的错误。使用 DBG 进行调试给了我一个算术错误,而 MSVC 给了我一个浮点异常,它缩小到除以 0。这是代码:

#include <stdio.h>
#include <math.h>
#include "cs50.h" // For MSVC, I used scanf_s() from stdio.h instead since cs50.h is not supported

long long Prompt(void); // Returns credit card number
int Validate(long long); // Returns checksum
void Report(long long); // Prints success

int main()
{
    long long CardNumber = Prompt();
    int CheckSum = Validate(CardNumber);
    if (!(CheckSum % 10)) {
        Report(CardNumber);
    } else {
        printf("INVALID\n");
    }
    return 0;
}

long long Prompt(void)
{
    printf("CARD NUMBER: ");
    long long CardNumber;
    CardNumber = GetLongLong();
    return CardNumber;
}

int Validate(long long CardNumber)
{
    int CheckSum = 0;
    int Digit = 0;
    int DigitCount = (int)(floor(log10l(CardNumber) + 1));
    for (int i = 2; i < DigitCount; i += 2) {
        Digit = 2 * ((CardNumber % (10 ^ i)) / (10 ^ (i - 1))); // BUG
        if (Digit > 9) {
            int BiDigit = Digit;
            Digit = 0;
            int SubDigit = 0;
            for (int j = 0; j < 2; i++) {
                SubDigit = (BiDigit % (10 ^ j)) / (10 ^ (j - 1)); // BUG
                Digit += SubDigit;
            }
        }
        CheckSum += Digit;
    }
    for (int i = 1; i < DigitCount; i += 2) {
        Digit = (CardNumber % (10 ^ i)) / (10 ^ (i - 1));
        CheckSum += Digit;
    }
    return CheckSum;
}

void Report(long long CardNumber)
{
    int DigitCount = (int)(floor(log10l(CardNumber) + 1));
    int Digit1 = (CardNumber % (10 ^ (DigitCount - 1))) / (10 ^ (DigitCount - 2)); // BUG
    int Digit2 = (CardNumber % (10 ^ (DigitCount - 2))) / (10 ^ (DigitCount - 3)); // BUG
    if (Digit1 == 4 && (DigitCount == 13 || DigitCount == 16))
        printf("VISA\n");
    else if (Digit1 == 3 && (Digit2 == 4 || Digit2 == 7) && DigitCount == 15)
        printf("AMERICAN EXPRESS\n");
    else if (Digit1 == 4 && (Digit2 >= 1 || Digit2 <= 5) && DigitCount == 16)
        printf("MASTERCARD\n");
    else
        printf("INVALID\n");
    return;
}
4

1 回答 1

4
Digit = 2 * ((CardNumber % (10 ^ i)) / (10 ^ (i - 1)));

^ is not a power operator, but bitwise xor in C and C++. Once i reaches 10, the expression 10 ^ i becomes zero.


BTW, in order to get digits from an integral number, it is better to avoid floating point operations (floor, log10l). A possible algorithm may look like this:

int DigitIndex = 0;
while (CardNumber > 0)
{
    int Digit = CardNumber % 10;
    CardNumber /= 10;

    // calculate check sum depending on parity of DigitIndex

    DigitIndex++;       
}
于 2014-09-13T01:50:39.283 回答