CS50 Pset1 Credit: Почему моя программа не отвечает? - PullRequest
0 голосов
/ 05 августа 2020

У меня практически нет опыта программирования и я зарегистрирован в CS50x на edX. В настоящее время я работаю над проблемой кредита для набора задач 1 (на языке C). Моя программа использует алгоритм Луна, чтобы определить, принадлежит ли номер кредитной карты American Express, MasterCard или Visa. Когда я тестирую программу, ввод номеров тестовых кредитных карт дает мне нежелательные ответы; Каждый вводимый мной действительный (тестовый) номер кредитной карты не дает никаких результатов.

Я борюсь с этим несколько дней. Был момент, когда моя программа распознала все 3 номера компании-эмитента кредитных карт, но разрешила вводить любое случайное число, в то время как я хотел, чтобы программа выводила «НЕДЕЙСТВИТЕЛЬНО», если это так.

Другая проблема, я ' У меня возникла ошибка, связанная с тем, что моя целочисленная переменная digitcount (см. код ниже) не объявлена ​​как переменная в одной строке кода (хотя есть несколько строк кода, в которых digitcount распознается нормально?)

Я исправил некоторые из этих ошибок, прочитав сообщения об ошибках, которые я получил, но иногда я не могу их понять, и просто возня с ними заканчивается их исправлением. Это не имеет никакого смысла для меня. (Например, удаление или перемещение скобок и замена == на =.)

Я также пробовал смотреть на коды других людей, но когда я пытаюсь использовать концепции, аналогичные тому, что я вижу, моя программа не работает.

Извините, если что-то из этого нечеткое или трудное для чтения! Несмотря на то, что я пытался научить себя тому, что мне нужно знать для выполнения этой работы, я часто запутываюсь, когда использую имена переменных, такие как «n», и нуждаюсь в некотором разделении между определенными частями кода, чтобы не чувствовать себя неорганизованным.

Я мог бы просто пропустить Кредит, так как я уже решил все другие задачи в Наборе задач 1, но я действительно хочу изучить и использовать любые знания, с которыми я сталкиваюсь, чтобы завершить и понять как можно больше.

Вот мой код! Большое спасибо всем, кто решит взглянуть и помочь мне понять, в чем я ошибаюсь!

#include <cs50.h>
#include <math.h>

int main(void)
{
    long long CCnumber;
    
    //prompts the user for a credit card number
    do
    {
        CCnumber = get_long_long("Enter your Credit Card Number: ");
    }
    while (CCnumber < 0);
    
    
    //--------------------
    
    
    //defines counter as a long type variable and digitcount as an integer type variable
    int counter = 0;
    int digitcount = 0;
    
    //loop the counts the digit-length of the credit card number
    while (counter > 0)
    {
        counter = CCnumber / 10;
        digitcount++;
    }
    
    
    //--------------------
    
    
    //grabs every other digit in the credit card number, starting from the second to last digit
    //% grabs the remainder of a number divided, while / grabs the quotient of the number divided
    int digit1 = (((CCnumber % 100) / 10) * 2);
        int digit1a = (digit1 / 10);
        int digit1b = (digit1 % 10);
    int digit2 = (((CCnumber % 10000) / 1000) * 2);
        int digit2a = (digit1 / 10);
        int digit2b = (digit1 % 10);
    int digit3 = (((CCnumber % 1000000) / 100000) * 2);
        int digit3a = (digit1 / 10);
        int digit3b = (digit1 % 10);
    int digit4 = (((CCnumber % 100000000) / 10000000) * 2);
        int digit4a = (digit1 / 10);
        int digit4b = (digit1 % 10);
    int digit5 = (((CCnumber % 10000000000) / 1000000000) * 2);
        int digit5a = (digit1 / 10);
        int digit5b = (digit1 % 10);
    int digit6 = (((CCnumber % 1000000000000) / 100000000000) * 2);
        int digit6a = (digit1 / 10);
        int digit6b = (digit1 % 10);
    int digit7 = (((CCnumber % 100000000000000) / 10000000000000) * 2);
        int digit7a = (digit1 / 10);
        int digit7b = (digit1 % 10);
    int digit8 = (((CCnumber % 10000000000000000) / 1000000000000000) * 2);
        int digit8a = (digit1 / 10);
        int digit8b = (digit1 % 10);
        
    //adds all the digits together
    int checksum1 = (digit1a + digit1b + digit2a + digit2b + digit3a + digit3b + digit4a + digit4b + digit5a + digit5b + digit6a + digit6b +digit7a +digit7b + digit8a +digit8b);
    
    //grabs all the other digits from the credit card number
    int otherdigit1 = ((CCnumber % 10) / 1);
    int otherdigit2 = ((CCnumber % 1000) / 100);
    int otherdigit3 = ((CCnumber % 100000) / 10000);
    int otherdigit4 = ((CCnumber % 10000000) / 1000000);
    int otherdigit5 = ((CCnumber % 1000000000) / 100000000);
    int otherdigit6 = ((CCnumber % 100000000000) / 10000000000);
    int otherdigit7 = ((CCnumber % 10000000000000) / 1000000000000);
    int otherdigit8 = ((CCnumber % 1000000000000000) / 100000000000000);
    
    //adds all the other digits together
    int checksum2 = (otherdigit1 + otherdigit2 + otherdigit3 + otherdigit4 + otherdigit5 + otherdigit6 + otherdigit7 + otherdigit8);
    
    //adds the checksum halfs together
    int TOTALchecksum = (checksum1 + checksum2);
    
    //checks the last digit of the total checksum
    int lastdigit =  (TOTALchecksum / 1);
    
    
    //--------------------
    
    
    //determines what the credit card number's first and second digits are (15-digit count)
    int startingdigit115 = (CCnumber / 100000000000000);
    int startingdigit215 = ((CCnumber / 10000000000000) % 10);
    
    int startingdigitsum15 = (startingdigit115 + startingdigit215);
    
    //determines what the credit card number's first and second digits are (16-digit count)
    int startingdigit116 = (CCnumber / 1000000000000000);
    int startingdigit216 = ((CCnumber / 100000000000000) % 10);
    
    int startingdigitsum16 = (startingdigit116 + startingdigit216);
    
    //determines what the cred card number's first and second digits are (13-digit count)
    int startingdigit113 = (CCnumber / 1000000000000);
    int startingdigit213 = ((CCnumber / 100000000000) % 10);
    
    int startingdigitsum13 = (startingdigit113 + startingdigit213);
    
    
    //--------------------

    if ((lastdigit == 0) && (digitcount == 15))
    {
        //determines if credit card number belongs to American Express
        if (startingdigitsum15 == 7 || startingdigitsum15 == 10)
        {
            printf("AMEX\n");
        }
    }
    
    else if ((lastdigit == 0) && (digitcount == 16))
    {
        //determines if credit card number belongs to MasterCard
        if (startingdigitsum16 == 6 || startingdigitsum16 == 7 || startingdigitsum16 == 8 || startingdigitsum16 == 9 || startingdigitsum16 == 10)
        {
            printf("MASTERCARD\n");
        }
    }
    
    else if ((lastdigit == 0 && digitcount == 13) || (lastdigit == 0 && digitcount == 16))
    {
        //determines if credit card number belongs to Visa
        if ((startingdigit113 == 4 || startingdigit116 == 4))
        {
            printf("VISA\n");
        }
    }
    
    else if ((lastdigit == 0 && digitcount != 13) || (lastdigit == 0 && digitcount != 15) || (lastdigit == 0 && digitcount != 16))
    {
        printf("INVALID\n");
    }
    
}```

1 Ответ

0 голосов
/ 05 августа 2020

Подсчет начальных нулей при вводе numeri c немного затруднен. Возможно, вам стоит прочитать номер карты как строку в массиве char *, используя scanf; затем проверьте CCNumber.

...
...
...
// max CCNumber char length is 16, plus 1 for string terminator '\0' = 17 chars
char CCNumber[17];
int notValidInput = 1;
int digitCount = 0;

while (notValidInput) {
    notValidInput = 0;
    scanf("%s", CCNumber);
    digitCount = 0;

    while (CCNumber[digitCount] != '\0') {
        // CCNumber character validation
        if (CCNumber[digitCount] < '0' || CCNumber[digitCount] > '9') {
            notValidInput = 1;
            printf("error: must contain numeric chars.\n");
            break;
        }
        else {
            digitCount++;
        }
    }
...
...
...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...