開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- Ruby (プログラミング言語)
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 7章(フロー制御), 7.5(練習問題)、うるう年、を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
うるう年
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby2.0 #-*- coding: utf-8 -*- print "先頭の年: " start = gets.chomp.to_i print "末尾の年: " stop = gets.chomp.to_i puts '間にあるすべてのうるう年一覧' year = start while year % 4 != 0 year += 1 end while year <= stop if year % 400 == 0 puts "#{year}年" elsif year % 100 != 0 puts "#{year}年" end year += 4 end
入出力結果(Terminal)
$ ./sample.rb 先頭の年: 1980 末尾の年: 2005 間にあるすべてのうるう年一覧 1980年 1984年 1988年 1992年 1996年 2000年 2004年 $ ./sample.rb 先頭の年: 1795 末尾の年: 1805 間にあるすべてのうるう年一覧 1796年 1804年 $ ./sample.rb 先頭の年: 1895 末尾の年: 1905 間にあるすべてのうるう年一覧 1896年 1904年 $ ./sample.rb 先頭の年: 1595 末尾の年: 1605 間にあるすべてのうるう年一覧 1596年 1600年 1604年 $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- start = int(input('先頭の年: ')) stop = int(input('末尾の年: ')) while start % 4 != 0: start += 1 for year in range(start, stop + 1, 4): if year % 400 == 0 or year % 100 != 0: print('{}年'.format(year))
入出力結果(Terminal)
$ ./sample.py 先頭の年: 1980 末尾の年: 2005 1980年 1984年 1988年 1992年 1996年 2000年 2004年 $ ./sample.py 先頭の年: 1795 末尾の年: 1805 1796年 1804年 $ ./sample.py 先頭の年: 1895 末尾の年: 1905 1896年 1904年 $ ./sample.py 先頭の年: 1595 末尾の年: 1605 1596年 1600年 1604年 $
0 コメント:
コメントを投稿