0

Im trying to get the sum with Luhn's algorithm with this credit card number: 4003600000000014

I'm getting this output: Sum single numbers: 4195600 Multiplied numbers: 0

I'm trying to get 13 and 7...

Appreciate some help!

#include <stdio.h>

int main(void)
{
    do
    {
        long card_number = get_long("Write your card's number:");
    } while (card_number < 0);

    // Sum of numbers that wont be multiplied by two
    int non_mult_numbers = card_number;
    while (non_mult_numbers > 0)
    {
        int last_digit = non_mult_numbers % 10;
        int sum_non_mult_numbers = sum_non_mult_numbers + last_digit;
        non_mult_numbers = non_mult_numbers / 100;
    }
    printf("Sum single numbers: %i\n", sum_non_mult_numbers);

    // Sum of numbers that will be multiplied by two and their digits added
    int mult_numbers = card_number;
    mult_numbers = mult_numbers / 10;
    while (mult_numbers > 0)
    {
        last_digit = mult_numbers % 10;
        int digit_times_two = last_digit * 2;
        int add_digits = add_digits + digit_times_two % 10 + digit_times_two / 10;
        mult_numbers = mult_numbers / 100;
    }
    printf("Multiplied numbers: %i\n", add_digits);
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 3
    $My hint: throw that code away and treat the credit card number a string and do the processing on the string. This is much simpler. – Jabberwocky Jun 23 '20 at 14:26

1 Answers1

0

While your code does not compile, I assume that several of your variables have wrong scope/lifetime.

Check add_digits, sum_non_mult_numbers, card_number.

Focus on the fact that {} mark a scope boundary for the variables defined inside.

  • Thank you! Is it bette to define my variables in the global scope? – Juan Pablo Sada Myt Jun 23 '20 at 14:50
  • No, variables should always be scoped as big as necessary, but as small as possible. The point is, that the code you provided can not possibly work like you stated, therefore nobody here can really help you. Just an exampe: In line 7 you create the varaible card_number. Its scpe ends in line 8. You use it in line 11. How do you get this to produce any results except compile errors? – BallisticTomato Jun 23 '20 at 15:01
  • If you want to make sure, that people around here can reproduce your results, you can check with common accessible tools like https://www.onlinegdb.com/ for example. This way you can make sure, that everybody can see the same behaviour as you do. – BallisticTomato Jun 23 '20 at 15:07