0

I tried to make a credit card payment calculator. Here's the whole code:

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

I'm getting an error message:

'calc_payment': undefined local variable or method 'payment' for main:Object (NameError)

1
  • 1
    Vori, a small suggestion: (payment / balance) * 100 or (better) 100 * payment / balance rather than payment / balance * 100 (clearer). Also, you could have puts "hi\n\n" rather than puts "hi"; puts; puts (stylistic difference only). Commented Oct 12, 2013 at 17:13

1 Answer 1

0

Your issue revolves around variable scope. payment has a local scope, and therefore the function calc_payment cannot "see" it. Here I modified your program so that you pass payment, balance, and apr into the calc_payment function. I also moved m_counter into the function as well.

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.