LoginSignup
2
2

More than 5 years have passed since last update.

プログラマの考えが・・身につく本より:数字を表す文字を整数型に変換する

Last updated at Posted at 2016-04-14

前回の続きから

問題:数値を最後まで読み終えたことを知る

これを解決するためにもっと小さな問題にしてみるとのこと
書籍はこちら『プログラマの考え方がおもしろいほど身につく本 問題解決能力を鍛えよう!』

問題:数字を表す文字を整数型に変換する

ユーザーが入力する0から9までの数字を表す文字を受け取るプログラムを書こう。受け取った文字をそれと同じ数字(0から9までの範囲)に変換し、変換後の数字を結果として表示する。

このような内容になっており解答例ではASCII文字コードの文字列数値と整数値の差が常に48あることを利用して引き算をしていました。
(文字列0の場合、"7"は文字コード55で求めたい整数値7なのでその差48とのこと)

この解答として描かれているC++

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)

###・・・・(ターミナル上での実行結果)
###>>> from ascii import number
###>>> number(str(7))
###Enter a one-digit number: 7
###Is the sum of digits: 7

以下修正コード記載//編集コードありがとうございます
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"

・・・・(ターミナル上
>>> number()
Enter a one-digit number: 7
The numerical value of the digit is:7


ASCII文字コードなるものをこの問題で少し勉強した気がします。
でもこのASCII文字コードってほかにどんなシーンで使いどころってあるんでしょうか?
UnicodeとASCIIコードあまり考えずにコピペしてたので考える機会になりました。

2
2
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2