C: Sum between two numbers returns ASCII value or letter

-1

Galera, I'm a C-language beginner, I'm challenging and I'm packing in a part of the code.

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

long long n = get_long_long("Number: ");

char card_number[15];
sprintf(card_number, "%lld", n);
int length_number = strlen(card_number);


for(int i = 0; i < length_number; i++)
{
        printf("A soma entre %c e %c é: %i \n", (int) card_number[i], (int)card_number[i], (int)(card_number[i] * 2));

}

printf("%s\n", card_number);

The get_long_long method is from an external library, from CS50 to be more accurate. It saves in the variable what the user wrote at the prompt according to what was requested ( "Number: " ).

Assuming that card_number[i] equals two, at the time of multiplying it ends up understanding that 2 as 50 (2 in the ASCII table equals 50) and the result gives 100, when in fact it should give 4! I've tried it in many ways and nothing! Depending on the type of % I put, it changes the value of the sum to a letter. I really want to figure it out and understand why.

    
asked by anonymous 14.07.2018 / 01:05

1 answer

1

It's not very clear in your code what it is that you wanted to do. But one way to convert a character in the range 0 - 9 to the numeric equivalent is to do this:

numero = caractere - '0';

In this case, the '0' is 48 according to the ASCII table. However, when using - '0' , the purpose of the code is more understood than putting - 48 .

So maybe what you wanted is this:

for (int i = 0; i < length_number; i++) {
    printf("A soma entre %c e %c é: %i \n",
            card_number[i], card_number[i], (card_number[i] - '0') * 2);
}

When you use %c , printf shows the value given as a character according to the ASCII table. The given value is always a number and the table is used only and only to find the character corresponding to that number. When you use %i or %d , the value is interpreted as a int and expressed in decimal notation.

See more about the modifiers here .

    
14.07.2018 / 17:23