检查用户使用gets.chomp输入的数字是否为ruby

时间:2017-06-29 15:30:38

标签: ruby

我现在已经找了很久,但找不到满意的答案。 我想知道如何检查用户输入的数字是否为浮点数。如果是浮点数,则它应该是无效数字。

我有一些东西,但结果总是为真/整数

这是我到目前为止所拥有的。

puts "What are the first number you want to divide"
number1 = gets.chomp.to_i
puts "What is the second number?"
number2 = gets.chomp.to_i

def is_float(variable)
return variable % 1 == 0
end

if (number1 == 0) && (number2 == 0)
puts "Invalid input"
elsif (is_float(number1) == false) || (is_float(number2) == false)
puts "Invalid input"

else
def divide(number1, number2)
    return number1 / number2
end

    division_result = divide(number1, number2)

def reminder(number1, number2)
    return number1 % number2
end

reminder_results = reminder(number1, number2)
puts ""
puts "Your result is #{division_result}"
puts "Your reminder is #{reminder_results}"
end

1 个答案:

答案 0 :(得分:0)

puts "What are the first number you want to divide"
number1 = gets.chomp.to_i
=> 100
puts "What is the second number?"
number2 = gets.chomp.to_i
=> 3

# Regular math
result_a = number1 / number2
puts "#{number1} / #{number2} = #{result_a}"
=> 100 / 3 = 33 # Integer class persists...

# Use a ruby library instead! Numeric#divmod
result_b = number1.divmod(number2)
puts "Result: #{result_b}"
=> [33, 1] # [quotient, modulus]