Rubyで逆ポーランド記法のプログラム書いてみました。
だいぶクソと思われますが、まあいいやお勉強です。
実行すると
4 2 /
2.0
4 1 /
4.0
5 2 + 2 2 + +
11.0
という感じ

以下コード

#
#逆ポーランド記法 Reverse Polish Notation
#
#07/4/15
#
class ReversePolishNotation
def initialize()
@stack = Array.new
end

def answer
return @stack.pop
end

def set(var)
if float_string?(var)
@stack.push(Float(var))
else
case var
when "+"
@stack.push(@stack.pop + @stack.pop)
when "-"
@stack.push((0 - @stack.pop) + @stack.pop)
when "*"
@stack.push(@stack.pop * @stack.pop)
when "/"
@stack.push((1 / @stack.pop) * @stack.pop)
end
end
end

#文字列が数字か判定
def float_string?(str)
begin
Float(str)
true
rescue ArgumentError
false
end
end
end


while line = gets
if line == "\n"
exit 0
end
rpn = ReversePolishNotation.new
line.split.each { |var| rpn.set(var) }
p rpn.answer
end

このブログの人気の投稿

Prusa i3 MK3S用 IKEA Lack エンクロージャー作ったぞ、3Dプリンターの入れる箱というか台だ、力作

エレキギター練習用にyousicianとオーディオ入力

Prusa i3 MK3S をBearエクストルーダーへ改造したよ