C: Sum between two numbers returns ASCII value or letter

Asked

Viewed 228 times

-1

Guys, I’m a beginner in the C language, I’m doing a challenge.

#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 method get_long_long is an external library, CS50 to be more exact. It stores in the variable what the user wrote in the prompt according to what was requested ("Number: ").

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

1 answer

1

It is not very clear in your code what it is you wanted to do. But a way to convert a character in the track 0-9 to the numerical equivalent is to do this:

numero = caractere - '0';

In the case, the '0' is 48 according to the ASCII table. However, when using - '0', the purpose of the code is more to understand than to put a - 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, the printf shows the given value as a character according to the ASCII table. The given value is at all times a number and the table is used only and only to find the character corresponding to that number. Already when you use %i or %d, the value is interpreted as a int and expressed with decimal notation.

See more about modifiers here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.