Home > Mobile >  Why is my else if function not working properly when I have checked to make sure the values make it
Why is my else if function not working properly when I have checked to make sure the values make it

Time:08-28

`

long get_number(void);
int get_digits(long creditnumber);
int calcfirst(long creditnumber);
bool checksum(long creditnumber, int digits);

int main(void)
{
    long creditnumber = get_number();
    int digits = get_digits(creditnumber);
    int firstdigit = calcfirst(creditnumber);
    int seconddigit = calcfirst(creditnumber);

if (digits != 13 && digits != 15 && digits != 16)
{
    printf("INVALID\n");
}
else
{
    if (checksum(creditnumber, digits))
    {
        if (firstdigit == 4)
        {
            printf ("VISA\n");
        }
        else if (firstdigit == 5 && (seconddigit > 0 && seconddigit < 6))
        {
            printf("MASTERCARD\n");
        }
        else if (firstdigit == 3 && (seconddigit == 4 || seconddigit == 7))
        {
            printf("AMEX\n");
        }
        else
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }
}
return 0;
}

long get_number(void)
{
     long creditnumber = get_long("Number: ");
     return creditnumber;
}

int get_digits(long creditnumber)
{
    int digits = 0;
do
{
    creditnumber /= 10;
    digits  ;
}
while (creditnumber != 0);

    return digits;
}

int calcfirst(long creditnumber)
{
    int firstdigit;
    int seconddigit;
    int firstnum;

long n = creditnumber;
while (n > 100)
{
    n /= 10;
}
firstnum = n;

firstdigit = firstnum / 10;
seconddigit = firstnum % 10;

return firstdigit;
return seconddigit;
}

`

In this code I request a credit card number and then check whether it is valid and then which type of card it is (for the CS50 Harvard course). The check works fine, but when it comes to looking at the first and second digits of the credit card number my code doesn't seem to work. It keeps returning one number as false when it should come back as an AMEX card because the first number is a three and the second number is a seven, and I've checked to ensure that this is true. Does anyone have any idea why this else if condition is not returning the way it should?

CodePudding user response:

You cannot return two values from a function and both firstdigit and seconddigit are same.

for efficient simply change this

int firstdigit = calcfirst(creditnumber);
int seconddigit = calcfirst(creditnumber);

to this:

int firstdigit = calcfirst(creditnumber);
int seconddigit = firstdigit;

CodePudding user response:

Your calcfirst function only returns the first number of the Credit card. The second return is never executed. So both firstdigit and seconddigit are actually the the same.

  • Related