Ruby 为什么我得到“得到”;未定义的局部变量“;毕达哥拉斯定理计算器?
我用Ruby制作了一个毕达哥拉斯定理计算器,它有一个bug/无法运行。错误是:Ruby 为什么我得到“得到”;未定义的局部变量“;毕达哥拉斯定理计算器?,ruby,geometry,algebra,pythagorean,Ruby,Geometry,Algebra,Pythagorean,我用Ruby制作了一个毕达哥拉斯定理计算器,它有一个bug/无法运行。错误是: undefined local variable or method `a2' 我想知道是否有人能帮忙 puts "Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle." a =
undefined local variable or method `a2'
我想知道是否有人能帮忙
puts "Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle."
a = gets.to_f
puts "please enter side B of your triangle."
b = gets.to_f
a**2 == a2
b**2 == b2
a2 + b2 = a2_b2
puts "The hypotenuse of your triangle is: #{ Math.sqrt(a2_b2)}"
您刚刚犯了两个小错误:
puts "Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle."
a = gets.to_f
puts "please enter side B of your triangle."
b = gets.to_f
a2 = a**2
b2 = b**2
a2_b2 = a2 + b2
puts "The hypotenuse of your triangle is: #{ Math.sqrt(a2_b2)}"
--
您的变量未定义
您将赋值与相等运算符(==
)混淆。当您声明:
a**2 == a2
您正在询问Ruby a2是否等于a2变量的值,该变量在示例代码中未定义。如果您打开一个新的Ruby控制台并在没有程序的情况下输入a2,您会在工作中看到相同的错误:
irb(main):001:0> a2
NameError: undefined local variable or method `a2' for main:Object
from (irb):1
from /usr/bin/irb:12:in `<main>'
irb(main):001:0> a2
NameError: undefined local variable or method `a2' for main:Object
from (irb):1
from /usr/bin/irb:12:in `<main>'
# In the console, paste one stanza at a time to avoid confusing the REPL
# with standard input.
print 'a: '
a = Float(gets)
print 'b: '
b = Float(gets)
c_squared = a**2 + b**2
hypotenuse = Math.sqrt(c_squared)