Introduction
Hello. It's guu.
Finally, this is the final installment of "The Reality of ASCII Codes".
This time, I would like to challenge the problem set in "[Part 1] ~ 49 even though it is 1? Input/output format ~"!
【problem】
Assign an integer to the variable num defined as a char type and print it with printf (“ %d ” );
However, make sure that the output value is the same as the input value.
* Hint: Subtract ' 0 ' from num.
"[Part 1] ~ 1 but 49 ? Input/output format ~" When
"[Part 2] - Correspondence between ASCII codes and characters -, as we learned in
If you input "1", simply output with printf ("%d"); will display "49".
This is when you output "1" input with getchar() with printf ("%d");
The cause was that the ASCII code corresponding to "1" (49) was output.
So how can I input "1" and output "1"?
The point is the ASCII code and a hint of the problem.
Commentary
"subtract '0' from num (now 1)"
If you think about it normally, even if you subtract 0 from a number, the value will not change.
But in this case, we're dealing with numbers entered "as characters."
So... it's converted to ASCII code.
Now, let's check the ASCII code table!
As you can see from the ASCII code table,
ASCII codes are applied sequentially to letters, numbers, and symbols.
For example, "0 to 1", "1 to 2", and the characters increase by 1, the corresponding ASCII code also increases by 1.
So, subtracting the ASCII code for 0 (48) from the ASCII code for 1 (49) gives "1".
By doing this, even if you output with printf (“ %d ”), you can output the same value as the input value.
Modifying the code based on this...
Let's go ahead and do it!
Yay!
Finally "1" was output \(^○^)/
One more note here!
If you look closely at the code, you'll notice that "0" is followed by "''".
This is not a decoration!
When subtracting 0 from num, the "0" must be an ASCII code.
The ' ' is needed to make the '0' be recognized as an ASCII code!
Summary
Since ASCII codes are in order, you can match input and output values by subtracting ' 0 ' from num .
■ guu's tweet
I learned a lot from just one problem.
Let's review well so as not to forget!
Check out the "Actual Reality of ASCII Codes" series! !
・ Actual state of ASCII code [Part 1] ~ 1 but 49 ? Input/output format ~
I tried to print 1 and got 49! ? When I searched for the cause, I found that it had something to do with the ASCII code.
・ Actual state of ASCII code [Part 2] ~ Correspondence between ASCII code and characters ~
We will approach the mystery that 1 has become 49!
・ Actual state of ASCII code [Part 3] Subtract '0' from num? ~
Finally, the meaning of "subtract '0' from num" becomes clear! !