2015-06-24 35 views
1

我試圖寫入一個小程序,將計算非常簡單的方程一個非常簡單的Ruby case語句求解器

Revenue = Costs * (1 + Profitpercentage) 

例如,121 = 110 *(1 + 0.10),當任何一個 - 只有3個元素中的一個缺失。

我想出了:

puts "What is your Revenue ?" 
inputRevenue = gets 
puts "What are your Costs ?" 
inputCosts = gets 
puts "What is your Profit percentage ?" 
inputProfitpercentage = gets 

revenue = inputRevenue.to_f 
costs = inputCosts.to_f 
profitpercentage = inputProfitpercentage.to_f 

case 
     when (revenue == nil) then 
     puts "Your Revenue is : #{costs * (1 + profitpercentage)}"  
     when (costs == nil) then 
     puts "Your Costs are : #{revenue/(1 + profitpercentage)}" 
     else (profitpercentage == nil) 
     puts "Your Profit percentage is : #{(revenue/costs) - 1}" 
end 

要指定要計算的元素,我直接跳過了答案(我只鍵入回車)。

它與Profitpercentage未知。

隨着Costs未知它給:

你的利潤百分比是:無限

隨着Revenue未知它給:

你的利潤百分比爲:-1.0

我哪裏錯了? (此外,它很笨拙......)

+0

儘量不要使用浮動。使用BigDecimal(to_d)。 – Elyasin

+0

空字符串'.to_f'爲零,而不是'nil'.''。to_f == 0',而不是'nil'。 – mudasobwa

回答

1

你不應該使用nil。只需將nil替換爲0即可。

這裏你應該做的,它會爲你工作:

puts "What is your Revenue ?" 
inputRevenue = gets 
puts "What are your Costs ?" 
inputCosts = gets 
puts "What is your Profit percentage ?" 
inputProfitpercentage = gets 

revenue = inputRevenue.to_f 
costs = inputCosts.to_f 
profitpercentage = inputProfitpercentage.to_f 

case 
     when (revenue == 0) then 
     puts "Your Revenue is : #{costs * (1 + profitpercentage)}"  
     when (costs == 0) then 
     puts "Your Costs are : #{revenue/(1 + profitpercentage)}" 
     else (profitpercentage == 0) 
     puts "Your Profit percentage is : #{(revenue/costs) - 1}" 
end 
+0

非常感謝您的回答。 – ThG

1
input = [] 
puts "What is your Revenue ?" 
input << gets.chomp  # get rid of carriage returns 
puts "What are your Costs ?" 
input << gets.chomp 
puts "What is your Profit percentage ?" 
input << gets.chomp 

input.map! do |rcp| 
    rcp.strip.empty? ? nil : rcp.to_f 
end 

case 
    when input[0].nil? 
    puts "Your Revenue is : #{input[1] * (1 + input[2])}"  
    when input[1].nil? 
    puts "Your Costs are : #{input[0]/(1 + input[2])}" 
    when input[2].nil? 
    puts "Your Profit percentage is : #{(input[0]/input[1]) - 1}" 
    else 
    puts "Oooups. Entered everything." 
end 
+0

首先,謝謝。當然,它是有效的。不過,我接受了@ Mourad的回答......因爲我明白這一點,原因很簡單,這與我自己的嘗試非常接近。我在Ruby中的知識不允許我掌握 - 但是 - 您的解決方案的全部含義。無論如何,再次感謝。 – ThG

+0

您隨時歡迎。 – mudasobwa