2012-09-13 40 views
1

这是我的代码试图计算coumpoung兴趣如何使用用户输入进行算术运算?

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 

这是我得到的一切烦恼

current_balance = current_balance + current_balance * interest_rate 

行了。如果我把它的代码是这样的,我得到字符串不能强制进入FixNum的错误。如果我在interest_rate后添加.to_i,那么我会多次乘上该行。我如何处理红宝石中的算术?

回答

2

gets将返回一个字符串\n。您的current_balanceinterest_rate变量是字符串,如"11\n""0.05\n"。所以如果你只使用interest_rate.to_i。根据fixnum,字符串和fixnum之间的运算符*将多次重复该字符串。尝试将它们转换为浮动。

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

使用'to_i'将会消除十进制值。 '“0.05 \ n”.to_i => 0'。应该使用'to_f'。 – oldergod

+0

@oldergod没错。我只是按照问题的方法。最好使用'to_f'。 – halfelf

+0

@halfelf,有道理。我仍然试图用Ruby来思考(不是用C#)。不容易。非常感谢你。 – Richard77

0

我也是一个新的Ruby程序员,一开始就遇到了数据类型问题。一个非常有用的故障排除工具是obj.inspect来找出你的变量是什么数据类型。

因此,如果在获得用户值后添加current_balance.inspect,则可以轻松地看到返回值为“5 \ n”,这是一个字符串对象。由于Ruby字符串对基本运算符(+ - * /)有自己的定义,这些定义并非您所期望的,您需要使用to_ *运算符之一(即前面提到的to_f)将其转换为可以使用数学运算符的对象。

希望这会有所帮助!