I'm working on pset1 credit. To identify the valid credit card number. First I ask users to input a long long, which I made it a int so that i can make sure it fit the first requirement(any number > 0). Then I want to identify each of the digits from small to large(right to left). To do this, I use a for loop from 0 to 16(temporary).In each loop, I divide the input by 10 ^ i first, then use % to get the remain divided by 10 ^ (i + 1). Last, I print them all to make sure I get them all.

but Not only I got the wrong number, but also got a error message runtime error: division by zero Floating point exception

I'm wonder which part did I do wrong, or I shouldn't use this method to solve this pset.

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

int main(void)
    printf("Card number: ");
    long long cn = get_long_long();
    int n = cn;

    if (n <= 0)
        float each;
        for (int i = 0; i < 16; i++)
            each = (n / (10 ^ i)) % (10 ^ (i + 1));//the i_th digits
            printf("%f\n", each);
        //int nth = (n / 10) % 10;
        //printf("%i\n", nth);

1 Answer 1


To answer the first part of your question

I'm wonder which part did I do wrong

It goes wrong right here:

long long cn = get_long_long();
int n = cn;

An integer in C cannot be bigger than 2147483647 (10 digits). And according to the exercise (https://docs.cs50.net/problems/credit/credit.html) credit card numbers need 13 or more digits ...

To the second part of your question

... or I shouldn't use this method to solve this pset.

I think this is not the correct way to isolate the digits.

For starters, if you want to handle single digits out of a row-of-digits, it's probably easiest to handle that row-of-digits as a row-of-characters (or a string).

Of course you can try to isolate single digits by means of arithmetic. But to do that, it is usually easiest to start at the end:

  • The last digit of number is number % 10
  • If you take away the last digit from number, you end up with number / 10

So there's no need to use powers of 10.

And to quote Cliff B:

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

  • Thanks for your answer, cuz I started learning programming with Python, I am kinda lack of the basic knowledge of cs. I'll watch the video and try your suggestion or some other idea coming up with your inspiration. Thanks again~!
    – 方威智
    Commented Oct 7, 2018 at 2:23

You must log in to answer this question.

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