0
0

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で1桁、2桁、3桁の整数の0埋めの方法(2通り)

Posted at

Rubyで1桁、2桁、3桁の整数の0埋めの方法を(2通り)の方法でプログラムを作成いたしました。

1通り目はsprintf関数を使う方法です。C言語を知っている方ならこちらでプログラムを書くと思います。

#sprintf関数を使う方法

puts '0から999までの整数を入力してください'
n = gets.to_i

puts '0で埋めて表示してください'
puts sprintf('%03d', n)

2通り目

#数値を入力します
N = gets.to_i
#数値を文字列に変換します
S = N.to_s
#Sのもじれつの長さを調べます
len = S.length
#文字列の長さが1,2,3でif文を作ります
if len == 3
   puts S
elsif  len == 2
   puts "0" + S
else
   puts "00" + S
end

どちらでプログラムを作成しても良いでしょう。

0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?