From the continuation of Last time
With this kind of content, in the example answer, subtraction was performed using the fact that there is always a difference of 48 between the character string numerical value and the integer value of the ASCII character code. (In the case of character string 0, "7" is the integer value 7 that you want to find with the character code 55, so the difference is 48)
C ++ depicted as this answer
char digit;
cout << "Enter a one-digit number: ";
cin >> digit;
int sum = digit - '0';
cout << "Is the sum of digits " << sum << "? \n";
#!/usr/bin/env python
#coding:utf-8
###def number(x):
### print("Enter a one-digit number:",x)
### digit = ord(x)
### sum = digit - ord('0')
### print("Is the sum of digits:",sum)
###・ ・ ・ ・(Execution result on the terminal)
###>>> from ascii import number
###>>> number(str(7))
###Enter a one-digit number: 7
###Is the sum of digits: 7
(Hereafter, the correction code is described)//Thank you for the edit code
from ConsoleOut import cout
def number():
cout << "Enter a one-digit number: "
digit = input()
value = int(digit)
cout << "The numerical value of the digit is:"+str(valule)+"\n"
・ ・ ・ ・ (On the terminal)
>>> number()
Enter a one-digit number: 7
The numerical value of the digit is:7
I feel that I learned a little about ASCII character encoding in this problem. But what other scenes do you use this ASCII character code for? Unicode and ASCII code I copied and pasted without thinking too much, so it was an opportunity to think about it.
Recommended Posts