我如何让两个变量除以 ruby?
how do i get two variables to divide in ruby?
我有我的变量,height
和 distance
。它们由用户输入。我想把它们分开,把结果变成一个新的变量,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
当我尝试 运行 这个时,它只是告诉我
`/': String can't be coerced into Float (TypeError)
有什么帮助吗?
计算前需要确认distance
和height
都是Integer或Float。
我会在使用 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
您收到此错误是因为高度仍然是一个字符串。这意味着您将浮点数 (distance.to_f) 除以字符串 (height)。
要修复它,请使用 to_f:
将高度转换为数字
`ratio = distance.to_f / height.to_f`
此外,最好检查输入的值是否确实是数字。默认情况下,如果您在其上调用 to_f 或 to_i,非数字字符串(其中没有数字的字符串)将被转换为零。
我有我的变量,height
和 distance
。它们由用户输入。我想把它们分开,把结果变成一个新的变量,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
当我尝试 运行 这个时,它只是告诉我
`/': String can't be coerced into Float (TypeError)
有什么帮助吗?
计算前需要确认distance
和height
都是Integer或Float。
我会在使用 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
您收到此错误是因为高度仍然是一个字符串。这意味着您将浮点数 (distance.to_f) 除以字符串 (height)。
要修复它,请使用 to_f:
将高度转换为数字`ratio = distance.to_f / height.to_f`
此外,最好检查输入的值是否确实是数字。默认情况下,如果您在其上调用 to_f 或 to_i,非数字字符串(其中没有数字的字符串)将被转换为零。