【问题标题】:Ruby programming error (undefined local variable)Ruby 编程错误(未定义的局部变量)
【发布时间】:2013-10-12 14:04:25
【问题描述】:

我尝试制作信用卡付款计算器。这是整个代码:

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': main:Object (NameError) 的未定义局部变量或方法'payment'

【问题讨论】:

  • Vori,一个小建议:(payment / balance) * 100 或(更好)100 * payment / balance 而不是payment / balance * 100(更清晰)。此外,您可以使用 puts "hi\n\n" 而不是 puts "hi"; puts; puts(仅风格差异)。

标签: ruby variables syntax-error undefined nameerror


【解决方案1】:

您的问题围绕变量范围展开。 payment 具有本地范围,因此函数 calc_payment 无法“看到”它。在这里,我修改了您的程序,以便您将paymentbalanceapr 传递给calc_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)

【讨论】:

    猜你喜欢
    • 2012-03-29
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多