我如何让两个变量在 ruby​​ 中除以?

Diy*_*ght 1 ruby math variables

我有我的变量,heightdistance. 它们由用户输入。我想将它们分开并将结果转换为一个新变量ratio.

print "How high are you?"
height = gets.chomp
print "How far are you from the landing strip?"
distance = gets.chomp
ratio = distance.to_f / height 
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,它只是告诉我

`/': String can't be coerced into Float (TypeError)
Run Code Online (Sandbox Code Playgroud)

有什么帮助吗?

dwe*_*zel 5

在计算之前,您需要确保distanceheight都是整数或浮点数。

我会在使用输入后立即将变量转换为浮点数gets.to_f(不需要,.chomp因为to_f也会删除换行符):

print "How high are you?"
height = gets.to_f
print "How far are you from the landing strip?"
distance = gets.to_f
ratio = distance / height 
Run Code Online (Sandbox Code Playgroud)