我试着写一个小程序来计算(非常)简单的等式
Revenue = Costs * (1 + Profitpercentage)
例如,121 = 110 *(1 + .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
要指定要计算的元素,我只需跳过答案(我只输入Enter)。
适用于Profitpercentage
未知。
如果Costs
未知,则会显示:
您的利润百分比是:无限
如果Revenue
未知,则会显示:
您的利润百分比是:-1.0
我哪里出错了? (此外,它很笨拙......)
答案 0 :(得分: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
答案 1 :(得分: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