为什么我在Pythagorean定理计算器中得到“未定义的局部变量”?

时间:2013-09-09 23:04:56

标签: ruby geometry algebra pythagorean

我在Ruby中制作了一个毕达哥拉斯定理计算器,它有一个错误/不运行。错误是:

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)}"

2 个答案:

答案 0 :(得分:1)

你刚刚犯了两个小错误:

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)}"

-

Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle.
3
please enter side B of your triangle.
4
The hypotenuse of your triangle is: 5.0

答案 1 :(得分:1)

您的变量未定义

您正在使用等于运算符(==)混淆赋值。当你声明:

a**2 == a2

你问Ruby是否 2 等于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>'

一些重构

虽然您可以通过确保在引用变量之前为变量赋值来修复代码,但您应该使代码更加惯用。例如,请考虑以下事项:

# 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)