vendredi 5 janvier 2018

CS50 Pset1 Credit (Issue with if statements returning invalid)

I'm having some issues with my if statement. It returns INVALID although I input a valid credit card number. It steps into the first if statement fine (I checked this by labelling the two INVLAIDs differently). To isolate whether it is an issue with my variables, I ran a printf of all the variables before the If statement begins and they are all correct. I'm guessing this means my If statement is written incorrectly?

Sample input: 378282246310005 , Output is INVALID. Expected output is AMEX.

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

int main(void)
{
    long long cc_number;

    do
    {
        printf("Number: ");
        cc_number = get_long_long();
    }
    while (cc_number < 0 || cc_number > 9999999999999999);

    long long length = cc_number;
    int count = 0;

    while (length != 0)
    {
        length = length / 10;
        count = count + 1;
    }

    long long slastdigit;
    long long lastdigit;
    int sums = 0;
    int sum = 0;

    for (long long i = 1; i < cc_number;)
    {
        lastdigit = (cc_number % (i * 10)) / i;
        sum = sum + (lastdigit % 10) + ((lastdigit % 100)/10);
        i = i * 100;
    }

    for (long long j = 1; j < cc_number/10;)
    {
        slastdigit = ((cc_number % (j*100))/(j*10))*2;
        sums = sums + (slastdigit % 10) + ((slastdigit % 100)/10);
        j = j * 100;
    }

    int checksum = 0;
    checksum = (sums + sum) % 10;
    slastdigit = slastdigit / 2;

    if (checksum == 0)
    {
        if (length == 15 && lastdigit == 3 && (slastdigit == 4 || slastdigit == 7))
        {
            printf("AMEX\n");
        }
        else if (length == 16 && (slastdigit == 1 || slastdigit == 2|| slastdigit == 3|| slastdigit == 4|| slastdigit == 5) && lastdigit == 5)
        {
            printf("MASTERCARD\n");
        }
        else if ((length == 13 || length == 16) && lastdigit == 4)
        {
            printf("VISA\n");
        }
        else
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }
}

I've searched similar questions and can't seem to see where I've gone wrong. Appreciate the assistance.

Aucun commentaire:

Enregistrer un commentaire