0

我用 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)}"
4

2 回答 2

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
于 2013-09-09T23:29:18.333 回答
1

您的变量未定义

您将赋值与相等运算符 ( ==) 混淆了。当您声明:

a**2 == a2

您在询问 Ruby a 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)
于 2013-09-09T23:50:05.840 回答