简体   繁体   中英

Ruby case statement for a very simple solver

I tried to write a small program that would calculate the (very) simple equation

Revenue = Costs * (1 + Profitpercentage)

eg, 121 = 110 * (1 + .10), when any one—and only one—of the 3 elements is missing.

I came up with:

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

To designate the element to be calculated, I simply skip the answer (I only type Enter).

It works with Profitpercentage unknown.

With Costs unknown it gives:

Your Profit percentage is : Infinity

With Revenue unknown it gives:

Your Profit percentage is : -1.0

Where did I go wrong? (furthermore, it is clumsy...)

You should not use nil . Just replace nil with 0 .

here what you should do and it will work for you:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM