编码新手,不确定在这里做错了什么。 这是我到目前为止的内容:
put "Enter degrees in Celsius:"
Celsius = gets.chomp
def celsius_to_fahrenheit (c)
fahrenheit = (c * 9/5)+32
end
puts "The temperature is #{celsius_to_farenheit (Celsius)} in Farenheit"
答案 0 :(得分:1)
此处已修复:
puts "Enter degrees in Celsius:"
celsius = gets.chomp
def celsius_to_fahrenheit(c)
fahrenheit = (c.to_f * 9/5)+32
end
puts "The temperature is #{celsius_to_fahrenheit(celsius)} in Farenheit"
celsius_to_farenheit
put
(应为puts
)调用不正确c
是字符串,而不是int / float。无法对字符串进行数学运算总的来说,最大的错误是不读取错误日志。当您运行该程序时,它将输出表明您的错误的错误。您应该一一纠正错误,直到程序编译/运行。不要只是随机地修复错误。阅读消息,考虑您做了什么以及您想做什么,然后解决该错误。
Traceback (most recent call last):
test.rb:1:in `<main>': undefined method `put' for
main:Object (NoMethodError)
Did you mean? puts
putc
这意味着您正在尝试在文件顶部调用一个函数(错误的put函数)。
Traceback (most recent call last):
test.rb:9:in `<main>': undefined method
`celsius_to_farenheit' for main:Object (NoMethodError)
Did you mean? celsius_to_fahrenheit
相同的症状,不同的疾病。
Traceback (most recent call last):
1: from test.rb:9:in `<main>'
test.rb:6:in `celsius_to_fahrenheit':
undefined method `/' for "666666666":String (NoMethodError)
看看它如何告诉我我需要知道的一切?
我将“ c”值转换为浮点数。默认情况下,用户的输入应解释为字符串。如果要将用户输入解释为浮点数而不是字符串,则必须将变量“转换”(转换)为浮点数。
您看到666666666
的原因是因为Ruby变得幻想起来。如果将一个字符串乘以一个整数N,则该字符串将重复N次。
例如"hello world" * 2 # hello worldhello world
答案 1 :(得分:0)
这是应该的代码。
puts "Enter degrees in Celsius:"
Celsius = gets.chomp.to_f
def celsius_to_farenheit (c)
fahrenheit = (c * 9/5)+32
end
puts "The temperature is #{celsius_to_farenheit (Celsius)} in Farenheit"
您正在犯某些错误