简体   繁体   中英

How to printf Variables correctly in C?

Today is the first time I use C and I tried some things like if, getchar(), etc. But now my problem is, that my third printf() in my code prints something it shouldnt. But I dont know where the problem is.

The loop should take the c integer and should add '1' every "loop-through". But when I input '5' the loop prints:

You entered: 54
You entered: 55
You entered: 56
You entered: 57
You entered: 58
You entered: 59
You entered: 60
You entered: 61
You entered: 62
You entered: 63
You entered: 64
You entered: 65
You entered: 66
You entered: 67

But it should print something like this:

You entered: 6
You entered: 7
You entered: 8
You entered: 9
You entered: 10
You entered: 11
You entered: 12
You entered: 13
You entered: 14
You entered: 15
You entered: 16
You entered: 17
You entered: 18
You entered: 19

My Code

#include <stdio.h>
int main()
{
    printf("Enter a value!: ");
    int c = getchar();
    printf("You entered: %c\n", c);

    int x = 1;

    while(x < 15) {
     x++;
     c++;
     printf("You entered: %d\n", c);
    }

    return 0;
}

When you use getchar() to scan a number, you scan it as a character. So the variable store the ascii value of 5 which is 53 . So when you print the value of c using %d it print the ascii value of c . As you increase the value by 1 before printing so it printed You entered: 54 (53+1). To get 5 you need to substruct the ascii value of '0' which is 48 from c . You can replace your 3rd printf with any of the two example below. Both will work fine.

printf("You entered: %d\n", c-'0');

or,

printf("You entered: %d\n", c-48);

Confusing numbers with representations of those numbers is a very common programming mistake. They are entirely different things. Five is the same number whether we write it as "five", "5", or "IIIII". But those are very different character sequences that represent that number.

The number five, the number of fingers you probably have on each of your hands, is not the same thing as the character '5' commonly used to represent that number. You are reading characters and then outputting them as if they were numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM