2012-09-13 41 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)將其轉換爲可以使用數學運算符的對象。

希望這會有所幫助!