0

I got a question on the credit. I don't know why it automatically quit. Like this:

~/pset1/credit/ $ ./credit
Number: 4003600000000014
~/pset1/credit/ $ 

Please see the code below.

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

int main(void)
{
    long long n;
    do
    {
        n = get_long_long("Number: ");
    }
    while (n < 0);
    
    int x;
    int sum = 0;
    
    for (x = 0; n != 0; n /= 10, x++)
    {
        if (x % 2 == 0)
        {
            sum = sum + n % 10;
        }
        else
        {
            int y = 2 * (n % 10);
            sum = sum + y / 10 + y % 10;
        }
    }

    if (sum % 10 == 0)
    {
        printf("good\n");
        if ( (n >= 340000000000000 && n < 350000000000000) || (n >= 370000000000000 && n < 380000000000000) )
        {
            printf("AMEX\n");
        }
        else if (n >= 5100000000000000 && n < 5600000000000000)
        {
            printf("MASTERCARD\n");
        }
        else if ( (n >= 4000000000000 && n < 5000000000000) || (n >= 4000000000000000 && n < 5000000000000000) )
        {
            printf("VISA\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }
}
1

It's not just "automatically quitting". It's running to completion.

Let me ask you a question. What would happen if sum % 10 doesn't equal 0? Would the program just bypass all those print statements? Isn't there something in the program spec about that?

Maybe you should put a couple strategic printf statements in the code temporarily to see what the values are in the variables? Try putting this in just before the last curly brace:

printf("sum = %i \n", i);

This will help you figure it out. If you're still really stuck on this, leave a comment and we can revisit it. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

3
  • Thanks for your help! I used your way, I found and fixed a few mistakes. It can work perfectly when I enter a invalid number, but once when I enter a real credit card number which is a very long number, it will not comparing and selecting which brand it is. It won't work after the code printf("good\n");. – Patrick Jul 10 '20 at 18:05
  • In the for loop, the cc number stored in n is modified, resulting in 0 being stored. The original cc number is not preserved, and 0 is always an invalid number. Try printing out the contents of n in the printf(good) statement. – Cliff B Jul 10 '20 at 18:37
  • You are right, thank you! – Patrick Jul 11 '20 at 14:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .