簡體   English   中英

如何編寫數學公式?

[英]How do I write a math formula?

我需要在代碼中編寫以下公式:

C ((i/100)(n/365)+1)

這意味着i應該除以100, n應該除以365,兩個結果必須相乘,結果數應加1,結果數應乘以C

我能夠編寫以下代碼,但無法修復的數學運算中有錯誤:

puts "Insert money to invest:"
money_invested = gets.to_i

puts "Indicate in days the period of deposit:"
time_investment = gets.to_i

puts "Indicate interest rate:"
interest_rate = gets.to_i

investment_calculation = money_invested * (([interest_rate / 100]  [time_investment / 365]) + 1)
puts "Your refund will be $#{investment_calculation.round(2)}."

嘗試這個:

investment_calculation = money_invested * (((interest_rate / 100) * (time_investment / 365) + 1))

1)您使用[]代替()

在ruby []對應於一個列表

2)您需要使用*(interest_rate / 100)(time_investment / 365)的結果相乘

編輯

如果您使用小數,則您的代碼將無法工作,則需要使用to_f而不是to_i

像這樣: interest_rate = gets.to_f

在Ruby中將兩個整數相除時,會得到整數除法(結果是整數):

irb(main):001:0> 1343/1000
#=> 1

如果需要浮點數,則需要至少兩個數字之一才能成為浮點值:

irb(main):002:0> 1343/1000.0
#=> 1.343
irb(main):003:0> 1343.0/1000
#=> 1.343

您可以通過將用戶輸入轉換為浮點數而不是整數(使用to_f代替to_i ),或者在公式中使用浮點常量來實現此目的。 萬一用戶輸入50.75的錢,第一個就足夠了並且很有意義。 "50.75".to_i #=> 50

puts "Insert money to invest:"
money_invested = gets.to_f

puts "Indicate in days the period of deposit:"
time_investment = gets.to_f

puts "Indicate interest rate:"
interest_rate = gets.to_f

investment_calculation = money_invested * (1 + interest_rate/100 * time_investment/365)
puts "Your refund will be $%.2f." % investment_calculation

請注意,我已經在%.2f使用String#%方法將您的數字格式化為兩位小數。 這是因為3.round(2)產生數字3.0而不是您期望的字符串"3.00"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM