0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby 問題13 条件演算子

Posted at

問題

3桁の正の整数を入力します。その整数の「百の位・十の位・一の位の和」について、
10の倍数(0,10,20,30...)からの差が

  • 2以内であるときは"True"

  • それ以外は"10の倍数との差は○です"

と表示されるようにプログラムを書く。

出力例

near_ten(144)→True
near_ten(214)→10の倍数との差は3です
near_ten(898)→10の倍数との差は5です
0も10の倍数に含むものとします。

ヒント

.rb
def near_ten(num)
  if 
    puts "True"
  elsif 
    puts "10の倍数との差は#{}です"
  else 
    puts "10の倍数との差は#{}です"
  end
end

near_ten()

条件分岐を用いれながら・・・

解答

.rb
def near_ten(num)
  total = (num/100) + (num/10 % 10) + (num % 10)
  remainder = total % 10
  if remainder <= 2 || remainder >= 8
    puts "True"
  elsif remainder <= 5
    puts "10の倍数との差は#{remainder}です"
  else 
    puts "10の倍数との差は#{10 - remainder}です"
  end
end

少しづつ分けて解説していきます

.rb
total = (num/100) + (num/10 % 10) + (num % 10)

上記の行で百の位・十の位・一の位を切り離して計算し、その合計をtotalに代入しています。

100の位の計算

num = 117の場合、num/100 つまり117/100は1.17となります。

Rubyでは整数同士(integer型)の計算だと返り値は整数になるので、小数点以下は切り捨てられて結果「1」になります。

10の位の計算

2桁の整数を10で割り、その値を10で割った際の余りが十の位になります。

num = 117の場合、117/10は11.7になります。整数同士は小数点以下の計算は行わないので、11になります。

11 % 10 は、11を10で割った際の余りを計算結果として返します。百の位の計算と同様に、小数点以下の計算は行わないので、余りは1となります。

よって、十の位は「1」となります。

1の位の計算

2桁の整数を10で割った際の余りが一の位になります。

num = 117の場合、117 % 10 は、117を10で割った際の余りを計算結果として返します。百の位の計算と同様に、小数点以下の計算は行わないので、余りは7となります。

よって、一の位は「7」になります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?