LoginSignup
0
0

More than 1 year has passed since last update.

簡単な計算を行うRubyプログラムの作成

Posted at

二桁以上の整数を入力すると、十の位と一の位の数字の足し算、十の位と一の位の数字の掛け算をそれぞれ行い、最後に2つの結果を足し合わせて出力するプログラムをRubyで作成してください。2桁の数字以外が入力として与えられた場合を考慮する必要はありません。

sample.rb
> 二桁の整数を入力してください
> 15

# 1 + 5と 1 * 5をそれぞれ計算

> 足し算結果と掛け算結果の合計値は11です
雛形
def addition(a, b)
  # 10の位と1の位の数字に対して、足し算を行う

end

def multiplication(a,b)
  # 10の位と1の位の数字に対して、掛け算を行う

end

def slice_num(num)
  # 10の位の計算

  # 1の位の計算

end

puts "二桁の整数を入力してください"
input = gets.to_i

X, Y = slice_num(input)
#  additionメソッドにX,Yを引数として渡し、処理結果を変数add_resultに代入する。

#  multiplicationメソッドにX,Yを引数として渡し、処理結果を変数multiple_resultに代入する。

puts "足し算結果と掛け算結果の合計値は#{add_result + multiple_result}です"

上記雛形を使って、解答して行きます。

解答
def addition(a, b)
  a + b
end

def multiplication(a,b)
  a * b
end

def slice_num(num)
  # 10の位
  tens_place = (num / 10) % 10
  # 1の位
  ones_place = num % 10
  return tens_place, ones_place
end

puts "二桁の整数を入力してください"
input = gets.to_i

X, Y = slice_num(input)
add_result = addition(X, Y)
multiple_result = multiplication(X, Y)

puts "足し算結果と掛け算結果の合計値は#{add_result + multiple_result}です"

部分的に見ていきます

def addition(a, b)
  a + b          # 10の位(a)と1の位(b)の数字を足す計算式
end

def multiplication(a,b)
  a * b          # 10の位(a)と1の位(b)の数字を掛ける計算式
end
def slice_num(num)
  # 10の位
  tens_place = (num / 10) % 10
  # 1の位
  ones_place = num % 10
  return tens_place, ones_place
end

tens_place = (num / 10) % 10
2桁の数字が35だったとします。
この計算式に当てはめて計算をすると、
(35 / 10) % 10 = 3 となります。

integerは整数のため、答絵に小数点は含みません。
35 / 10 = 3
3 % 10 = 3

ones_place = num % 10
35 % 10 = 5

X, Y = slice_num(input)
add_result = addition(X, Y)
#  additionメソッドにX,Yを引数として渡し、処理結果を変数add_resultに代入

multiple_result = multiplication(X, Y)
#  multiplicationメソッドにX,Yを引数として渡し、処理結果を変数multiple_resultに代入
0
0
0

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
0
0