Richard77
Richard77

Reputation: 21621

How can I do arithmetics with user inputs?

This is my code trying to calculate the coumpoung interest

def coumpoundinterest
 print "Enter the current balance: "
 current_balance = gets
 print "Enter the interest rate: "
 interest_rate = gets
 _year = 2012
 i = 0
 while i < 5 do

  current_balance = current_balance + current_balance * interest_rate
  puts "The balance in year " + (_year + i).to_s + " is $" + current_balance.to_s

  i = i + 1  
 end
end

This is the line where I'm getting all the troubles

current_balance = current_balance + current_balance * interest_rate

If I keep the code the way it is, I get an error that string cannot be forced into FixNum. If I add .to_i after interest_rate, then I get the line multiply several times. How can I deal with arithmetics in ruby?

Upvotes: 1

Views: 78

Answers (2)

blaushka
blaushka

Reputation: 1

I am a new Ruby programmer also and had trouble with data types at first. A very useful troubleshooting tool is obj.inspect to figure out exactly what data types your variables are.

so if you add current_balance.inspect after you get the user value you can easily see the return value is "5\n" which is a string object. Since Ruby strings have their own definitions of the basic operators (+ - * /) which aren't what you'd expect you'll need to use one of the to_* operators (namely to_f as already mentioned) to convert it to an object which you can use math operators on.

Hope this helps!

Upvotes: 0

halfelf
halfelf

Reputation: 10107

gets will return a string with \n. Your current_balance and interest_rate variables are strings like "11\n" "0.05\n". So if you only use interest_rate.to_i. The operator * between a string and a fixnum will repeat the string several times according to the fixnum. Try to convert them into float both.

current_balance = gets.to_f
interest_rate = gets.to_f
...
current_balance *= (1+interest_rate)

Upvotes: 2

Related Questions