Сделал сценарий на Лонг Альг. Невозможно понять, как создавать и вызывать функции четко для пересмотренного скрипта - PullRequest
3 голосов
/ 10 апреля 2020

Я новичок в программировании. В настоящее время я довольно строго провожу онлайн-лекции и выполнил задание, используя алгоритм Луна. Это всего лишь один сценарий, который выполняется напрямую, но для своего будущего я хочу научиться кодировать более эффективно, когда проекты становятся больше.

Вот тут и возникает моя проблема. Кажется, я не понимаю, как определить или вызвать функции правильно и не в состоянии преобразовать мой сценарий во что-то более «эффективное».

(Все уже отправлено, и мой сценарий, по словам бота, прекрасно выполняет задачу, поэтому я не пытаюсь наполовину чтобы моя работа здесь была ясна.)

Это законченный скрипт, в котором используется только функция main , и мне потребовалось 12-15 часов, чтобы она заработала без ошибок. с самого начала. Все написано в C

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

int main(void)
{
    // this grabs the number and verifies the correct amount of digits
    int count;
    long number = 0;
    do
    {
        number = get_long("Number: ");
        count = (number == 0) ? 1 : (log10(number) + 1);
        if (count < 13 || count == 14 || count > 16)
        {
            printf("INVALID\n"); // This is to satisfy the uni. bot command check. Need a EOF for numbers with the wrong amount of digits.
            return (0);
        }
    }
    while (count < 13 || count == 14 || count > 16);
    //printf("Digits: %i\n", count);       // test print for debugging

    //This finds the first two digits of input number

    long int two = number;
    while (two >= 100)
    {
        two = two / 10;
    }
    //printf("First two numbers: %li\n", two);      // test print for debugging

    // verifies card using mod10 (Luhn's)
    long sum = 0;
    long bigdigit = 0;
    //printf("\nLUHN Number: %li\n\n", number);     // test print for debugging
    if (count == 13 || count == 15)
    {
        count += 1;
    }
    for (int i = count; i > 0; i--)
    {
        if (i % 2 == 0)
        {
            sum += (number % 10);
        }
        else
        {
            bigdigit = (2 * (number % 10));
            sum += (bigdigit / 10 + bigdigit % 10);
        }
        number = (number / 10);
        //printf("\nI : %i\n", i);      // test print for debugging
        //printf("Sum: %li\n", sum);        // test print for debugging
        //printf("Number: %li\n", number);      // test print for debugging
    }
    if (sum % 10 == 0)
    {
        printf("VALID\n");
    }
    else
    {
        printf("INVALID\n");
        return (0);
    }

    // checks what type of card

    if (two == 34 || two == 37)
    {
        printf("AMEX\n");
        return (0);
    }
    else if (two >= 51 && two <= 55)
    {
        printf("MASTERCARD\n");
        return (0);
    }
    else if (two >= 40 && two <= 49)
    {
        printf("VISA\n");
        return (0);
    }
    else
    {
        printf("INVALID\n");
        return (0);
    }
}

Я пытался разделить его на 3 функции main для вызова.

  • long input_number ();
  • bool luhn_check ();
  • void company_check ();

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


«Пересмотренный» скрипт v2

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

long input_number(long CCN);
int counter(long CCN, int count);
bool luhn_check(long CCN, int count);
long firsttwo(long CCN, long two);
void card_type(long two);


int main()
{
    long CCN = 0;
    int count = 0;
    long two = 0;
    CCN = input_number(CCN);
    count = counter(CCN, count);

    //printf("CCN: %li\n", CCN); //debugging purposes
    //printf("Digits: %i\n", count); //debugging purposes
    luhn_check(CCN, count);
    two = firsttwo(CCN, two);
    //printf("First Two: %li\n", two); //debugging purposes
    card_type(two);
}


    // this grabs the number and verifies the correct amount of digits
long input_number(long CCN)
{
    int count = 0;
    do
    {
        CCN = get_long("Number: ");
        count = (CCN == 0) ? 1 : (log10(CCN) + 1);
        if (count < 13 || count == 14 || count > 16)
        {
            //printf("INVALID\n"); // This is to satisfy the uni. bot command check. Need a EOF
            //return (0);
        }
    }
    while (count < 13 || count == 14 || count > 16);   
    return (CCN);
}

int counter(long CCN, int count)
{
 do
    {
        count = (CCN == 0) ? 1 : (log10(CCN) + 1);
    }
    while (count < 13 || count == 14 || count > 16);   
    return (count);   
}

    // verifies card using mod10 (Luhn's)
bool luhn_check(long CCN, int count)
{
    long sum = 0;
    long bigdigit = 0;
    //printf("\nLUHN Number: %ld\n\n", CCN);     // test print for debugging
    if (count == 13 || count == 15)
    {
        count += 1;
    }
    for (int i = count; i > 0; i--)
    {
        if (i % 2 == 0)
        {
            sum += (CCN % 10);
        }
        else
        {
            bigdigit = (2 * (CCN % 10));
            sum += (bigdigit / 10 + bigdigit % 10);
        }
        CCN = (CCN / 10);
        //printf("\nI : %i\n", i);      // test print for debugging
        //printf("Sum: %li\n", sum);        // test print for debugging
        //printf("Number: %li\n", CCN);      // test print for debugging
    }
    if (sum % 10 == 0)
    {
        printf("VALID\n");
        return (true);
    }
    else
    {
        printf("INVALID\n");
        return (false);
    }
}

            // grabs the first two numbers
long firsttwo(long CCN, long two)
{
    two = CCN;
    //printf("TWO CCN: %li\n", two); // debugging purposes
    while (two >= 100)
    {
        two = two / 10;
    }
    return (two);
}

            // finds card type and ends
void card_type(long two)
{
    if (two == 34 || two == 37)
    {
        printf("AMEX\n");
        //return (0);
    }
    else if (two >= 51 && two <= 55)
    {
        printf("MASTERCARD\n");
        //return (0);
    }
    else if (two >= 40 && two <= 49)
    {
        printf("VISA\n");
        //return (0);
    }
    else
    {
        printf("INVALID\n");
        //return (0);
    }
}

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

Помимо запуска программы с строкой вместо b, могу ли я что-нибудь сделать более эффективно?

1 Ответ

0 голосов
/ 10 апреля 2020

Позвольте мне начать с нескольких заметок о вашей функции input_number:

long input_number()
{
    // this grabs the number and verifies the correct amount of digits
    int count;
    [ .... ]

    while (count < 13 || count == 14 || count > 16);
    // Once this while loop starts, it will never terminate!
    // if count starts at 10 (which is less than 13), the body says "do nothing".
    // so count will continue to be unchanged, and the while-loop will continue to run.

    return (0);  // Code after a return statement will never be reached
                 // So your printf-statement below will NEVER happen.
                 // It also seems unlikely you want to return Zero.
                 // You probably want to return count, or some other value.

    printf("Digits: %i\n", count);       // test print for debugging
}
...