0

else用户没有输入12的地方,脚本应该在显示错误消息后重新开始。我怎样才能做到这一点?

    puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
input = gets


if input == 1
    puts "Please enter degrees in Celcius."
    celcius = gets
    fahrenheit = (celcius.to_i * 9 / 5) + 32
    print "The result is "
    print fahrenheit
    puts "."
elseif input == 2
    puts "Please enter degrees in Fahrenheit."
    fahrenheit = gets
    celcius = (fahrenheit.to_i / 9 * 5) - 32
    print "The result is:"
    print celcius
    puts "."
else
    puts "Please enter option 1 or 2"
end
4

2 回答 2

4

您需要将整个事物包装在一个while循环中并将变量初始化input为一个值,例如nil.

循环的while条件应该检查​​值是 1 还是 2,并且可能需要将其转换为整数,.to_i因为gets将返回一个字符串。

# initialize to nil
input = nil

# Check if the current value (integer) is 1 or 2
while !([1,2].include?(input))
  puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"

  # Convert the string to an int after getting it as input
  input = gets.to_i

  if input == 1
    puts "Please enter degrees in Celcius."
    celcius = gets
    fahrenheit = (celcius.to_i * 9 / 5) + 32
    print "The result is "
    print fahrenheit
    puts "."
  # elsif here, not elseif!!
  elsif input == 2
      puts "Please enter degrees in Fahrenheit."
      fahrenheit = gets
      celcius = (fahrenheit.to_i / 9 * 5) - 32
      print "The result is:"
      print celcius
      puts "."
  else
      puts "Please enter option 1 or 2"
  end
end

事实上,在测试否定条件时while,使用until循环(Ruby 与许多其他语言不同)比使用循环更具可读性:

until [1,2].include?(input)
  ...
end

[1,2].include?(input)是一种更流畅的写作方式

 if input == 1 || input == 2

...这很容易扩展为数组中的其他值。

于 2013-01-26T21:17:27.430 回答
0

这就是它使用一个函数。

puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
def convert
    input = gets
    if input == 1
        puts "Please enter degrees in Celcius."
        celcius = gets
        fahrenheit = (celcius.to_i * 9 / 5) + 32
        print "The result is "
        print fahrenheit
        puts "."
    elseif input == 2
        puts "Please enter degrees in Fahrenheit."
        fahrenheit = gets
        celcius = (fahrenheit.to_i / 9 * 5) - 32
        print "The result is:"
        print celcius
        puts "."
    else
        puts "Please enter option 1 or 2"
        convert()
    end
end

如果 input != (2 || 1) 也可以工作。

于 2013-01-27T02:33:22.533 回答