如何在 Ruby 中将英尺和英寸转换为英寸?

时间:2021-01-09 21:56:13

标签: ruby

基本上,有人告诉我,如果我想在编程方面做得更好,我应该选择一个项目并坚持下去。我选择编写一个 BMI 计算器。这是代码。

def get_values()
    puts("Please enter your height in metres.")
    height = gets.to_f
    puts("Please enter your weight in kilograms.")
    weight = gets.to_f
    bmi = ((weight) / (height * height))
    puts("Your BMI is: " + bmi.to_s)
    if (bmi < 18.5)
        puts("You are underweight.")
    elsif (bmi > 18.5) and (bmi < 25.0)
        puts("You are a healthy weight.")
    elsif (bmi > 25) and (bmi < 30)
        puts("You are overweight.")
    elsif (bmi > 30)
        puts("You are obese.")
    end
end

  def get_values_imperial()
    puts("Please enter your height in inches.")
    height = gets.to_f
    puts("Please enter your weight in pounds.")
    weight = gets.to_f
    bmi = (weight * 703) / (height * height)
    puts("Your BMI is: " + bmi.to_s)
    if (bmi < 18.5)
        puts("You are underweight.")
    elsif (bmi > 18.5) and (bmi < 25.0)
        puts("You are a healthy weight.")
    elsif (bmi > 25) and (bmi < 30)
        puts("You are overweight.")
    elsif (bmi > 30)
        puts("You are obese.")
    end
end
 
  def main()
    puts("Welcome to the BMI calculator. Would you like to continue with metric or imperial values?")
    answer = gets.chomp
    if (answer == "metric") or (answer == "Metric")
      get_values()
    elsif (answer == "imperial") or (answer == "Imperial")
        get_values_imperial()
    else
      ("Unsupported unit of measurement.")
    end
  end
  
  main()
  

基本上,问题是这样的:大多数人不知道他们的身高(以英寸为单位),或者我认为是这样。我希望用户能够输入高度,例如。 6'1",以英尺和英寸为单位。这是否可能不使用 Numeric 类?

1 个答案:

答案 0 :(得分:0)

与您的问题标题一致:

str = "6'11\""

def to_inch(x)
  ( x.split("'")[0].to_i * 12 ) +
  x.split("'")[1].to_i
end

to_inch(str)
=> 83

如果你想完成这个例子,你还应该检查 str 的格式。

编辑: 如果您想发挥创造力,这里有一个没有 to_i 的版本:

h = {}
0.upto(12) { |x| h[x.to_s] = x }

def to_inch(x, ha)
  ( ha[x.split("'")[0]] * 12 ) +
  ha[x.split("'")[1].chomp("\"")]
end

to_inch(str, h)
=> 83