计算变量

时间:2016-12-25 18:28:07

标签: ruby

我正在构建一个跑步计算器,它要求运行距离,然后是时间。我设置了一个变量来按时间划分距离,并希望将其打印到屏幕上:

puts "Pace Calculator"

puts "What is the distance in KM?"
distance = gets

puts "What is the time in minutes?"
time = gets

#this is where the error occurs, how do I do a calculation in a variable?
pace = "#{distance}/#{time}"

puts "Your pace is #{pace}" 

但它似乎没有正常工作。如何设置变量进行计算?

2 个答案:

答案 0 :(得分:1)

您应该将您遇到错误的行更改为:

pace = distance.to_f / time.to_f

您目前正在尝试在字符串中执行此操作,这似乎没有多大意义。 to_f将字符串(从输入)转换为浮点数。

答案 1 :(得分:0)

你可以做这样的事情

puts "Pace Calculator"

puts "What is the distance in KM?"
distance = gets

puts "What is the time in minutes?"
time = gets


#this is where the error occurs, how do I do a calculation in a variable?
puts "#{distance}/#{time}"

pace = distance.to_f / time.to_f

puts "Your pace is #{pace}"