0

Below is the block of code that i have issue with. I'm using this method to extract the digits: num[i] = (num % pow(10, i))/pow(10, i-1). The pow1 and pow2 variables print out correctly, but "digit" is always 0. Can someone help me understand why? Thank you so much!

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

int sum_digits(int product);
int main(void)
{
    long card;
    int count = 0;
    int i = 0;
    do //prompting for card number
    {
        card = get_long("Card Number: ");
    }
    while (card < 3000000000000);

    while (card > 0) // get the number of digits
        {
            card /= 10;
            count = count + 1;
        }

    long total_sum = 0;
    for ( i = 1; i <= count; i++) //extracting individual digits
    {
        long pow1 = pow(10,i), pow2 = pow(10, i-1);
        long digit = (card % pow1) / pow2;
        printf("%ld\n", pow1);
        printf("%ld\n", digit);
    }
}

1 Answer 1

1

What is the value of card after this loop?

while (card > 0) // get the number of digits
        {
            card /= 10;
            count = count + 1;
        }

In this exercise, and very often in general, it is a good idea to treat user's input as a constant value. You might want to declare another variable to use for the length calculation.

1
  • Ahhh i see the issue now, so silly of me. Thank you!
    – Mai N.
    May 27, 2019 at 16:43

You must log in to answer this question.

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