CS50 Week1:信用任务改进?

CS50 Week1: credit task improvements?

首先:我之前没有任何编码经验,只用了第一周他们给我们的工具就花了将近一整天的时间来完成这项任务。

我确实做到了,但是代码看起来不太漂亮,我想看看我是否可以以某种方式改进它? 我怎样才能使 Luhn 算法更优雅或最后的布尔逻辑(参见 Mastercard OR orgy)?

如有任何帮助,我将不胜感激:)

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

int main(void)
{
    long num = get_long("Number: ");
    int sum_eo, sum_no;

    // determine length of input
    int length = 0; 
    for (long i = 1; i < num; i *= 10)
    {
        length++;
    }

    // determine the first two numbers of the input
    long start_digits = num;
    for (int i = 0; i < (length - 2); i++)
        {
            start_digits /= 10;
        }

    // Luhn-algorithm
    // first every other number from the back
    for (long i = 100; i < (num * 10); i = i*100)
    {
        int every_other = (((num % i)- (num % (i / 10))) / (i/10));
            if ((every_other * 2) < 10)
            {
                sum_eo = sum_eo + (every_other * 2);
             }
            else
            {
                 sum_eo = sum_eo + 1 + ((every_other*2) % 10);
             }
    }
    // then the other numbers
    for (long i = 10; i < (num * 10); i = i*100)
    {
        int every_no = (((num % i)- (num % (i / 10))) / (i/10));
        sum_no = sum_no + every_no;
    }

    //calculate checksum and choose which card
    int checksum = (sum_eo + sum_no) % 10;
    if (checksum == 0) // 
    {
        if (length == 15 && (start_digits == 34 || start_digits == 37))
        {
            printf("AMEX\n");
        }
        else if ((length == 13 || length == 16) && (start_digits / 10) == 4)
        {
            printf("VISA\n");
        }
        else if (length == 16 && (start_digits == 51 || start_digits == 52 || start_digits == 53 || start_digits == 54 || start_digits == 55))
        {
            printf("MASTERCARD\n");
        }
        else
            printf("INVALID\n");
    }
    else
        printf("INVALID\n");

}

您可以在此处进行的一项潜在更改:

    else if (length == 16 && (start_digits == 51 || start_digits == 52 || start_digits == 53 || start_digits == 54 || start_digits == 55))

您可以改为这样做:

    else if (length == 16 && (start_digits >= 51 && start_digits <= 55))