0

我试着做一个信用卡支付计算器。这是整个代码:

m_counter = 0

def calc_payment
  payment_percentage = payment / balance * 100
  monthly_apr = apr / 12
  while balance > 0
   m_counter = m_counter + 1
   balance = balance / 100 * monthly_apr
   balance = balance - payment
  end
  puts
  puts "Monthly payment: $" + payment
  puts "Balance payoff: " + m_counter + " months" 
end

puts "Welcome to your credit card payment calculator!"
puts

puts "Please tell me your credit card balance."
balance = gets.chomp.to_f

puts "Please enter your interest rate %."
apr = gets.chomp.to_f

puts "How much $ would you like to pay every month?"
payment = gets.chomp.to_f

calc_payment

我收到一条错误消息:

'calc_payment': 未定义的局部变量或方法'payment' 用于 main:Object (NameError)

4

1 回答 1

0

您的问题围绕变量范围展开。payment具有本地范围,因此该函数calc_payment无法“看到”它。在这里,我修改了您的程序,以便您将paymentbalance和传递aprcalc_payment函数。我也m_counter进入了这个功能。

def calc_payment(payment, balance, apr)
  m_counter = 0
  payment_percentage = payment / balance * 100
  monthly_apr = apr / 12

  while balance > 0
   m_counter = m_counter + 1
   balance = balance / 100 * monthly_apr
   balance = balance - payment
  end

  puts
  puts "Monthly payment: $" + payment
  puts "Balance payoff: " + m_counter + " months" 

end

puts "Welcome to your credit card payment calculator!"
puts

puts "Please tell me your credit card balance."
balance = gets.chomp.to_f

puts "Please enter your interest rate %."
apr = gets.chomp.to_f

puts "How much $ would you like to pay every month?"
payment = gets.chomp.to_f

calc_payment(payment, balance, apr)
于 2013-10-12T14:37:33.403 回答