Ruby 預金システムのアルゴリズム問題
問題
銀行口座に10万円の預金残高があり、お金を引き出すプログラムを作成流問題です。
自分の解答
def withdraw(balance, amount) fee = 110 # 手数料 # 引き落とし額と残高を表示する、もしくは残高より多く引き落としたら残高不足と表示 balance = balance - amount -fee if balance >= 0 puts "#{amount}円引き落としました。残高は#{balance}円です" else puts "残高不足です" end end balance = 100000 # 残高 puts "いくら引き落としますか?(手数料110円かかります)" amount = gets.to_i withdraw(balance, amount)
模範解答
def withdraw(balance, amount) fee = 110 if balance >= (amount + fee) balance -= (amount + fee) puts "#{amount}円引き落としました。残高は#{balance}円です" else puts "残高不足です" end end balance = 100000 puts "いくら引き落としますか?(手数料110円かかります)" amount = gets.to_i withdraw(balance, amount)
100,000円を基準にするか、0円を基準にするかの違いです。