Ruby中的除法,错误

Ruby中的除法,错误,ruby,Ruby,这是我学习Ruby的第一天。我正试图编写一个Ruby程序,询问用户一顿饭的费用,然后询问他们愿意付多少小费,然后进行计算并打印出结果。我写了以下内容: puts "How much did your meal cost?" cost = gets puts "How much do you want to tip? (%)" tip = gets tip_total = cost * (tip/100.0) puts "You should tip $" + tip_total 当我尝试在终端

这是我学习Ruby的第一天。我正试图编写一个Ruby程序,询问用户一顿饭的费用,然后询问他们愿意付多少小费,然后进行计算并打印出结果。我写了以下内容:

puts "How much did your meal cost?"
cost = gets
puts "How much do you want to tip? (%)"
tip = gets
tip_total = cost * (tip/100.0)
puts "You should tip $" + tip_total
当我尝试在终端中运行它时,我收到以下错误消息:

ip_calculator.rb:7:in `<main>': undefined method `/' for "20\n":String (NoMethodError)
ip\u calculator.rb:7:in`':用于“20”的未定义方法“/”\n:String(NoMethodError)

我不知道这条消息意味着什么,有人能帮我理解错误消息和/或我的代码有什么问题吗?谢谢。

因为当您从标准输入中输入值时,它是一个
字符串。ruby不能将字符串除以100

以下是一个工作示例:

#!/usr/bin/env ruby

puts "How much did your meal cost?"
cost = gets.to_f
puts "How much do you want to tip? (%)"
tip = gets.to_f
tip_total = cost * (tip/100.0)
puts "You should tip $ #{tip_total.round(2)}"
将所有输入值转换为浮点值,进行计算,然后打印舍入值

[retgoat@iMac-Roman ~/temp]$ ./calc.rb
How much did your meal cost?
123.45
How much do you want to tip? (%)
12.43
You should tip $ 15.34

因为当您从标准输入值时,它是一个
字符串
。ruby不能将字符串除以100

以下是一个工作示例:

#!/usr/bin/env ruby

puts "How much did your meal cost?"
cost = gets.to_f
puts "How much do you want to tip? (%)"
tip = gets.to_f
tip_total = cost * (tip/100.0)
puts "You should tip $ #{tip_total.round(2)}"
将所有输入值转换为浮点值,进行计算,然后打印舍入值

[retgoat@iMac-Roman ~/temp]$ ./calc.rb
How much did your meal cost?
123.45
How much do you want to tip? (%)
12.43
You should tip $ 15.34
我的代码有什么问题

返回一个字符串<代码>获取
不尝试解释输入,它只传递接收到的字符。如果在终端中键入20return,则
gets
将返回一个包含相应字符
“2”
“0”
“\n”
的字符串

要转换值,我将使用内置转换方法或:

to_i
to_f
不同,如果输入非数值,这些方法将引发错误

我的代码有什么问题

返回一个字符串<代码>获取不尝试解释输入,它只传递接收到的字符。如果在终端中键入20return,则
gets
将返回一个包含相应字符
“2”
“0”
“\n”
的字符串

要转换值,我将使用内置转换方法或:

to_i
to_f
不同,如果输入非数值,这些方法将引发错误

cost = Float(gets)