Вопрос

I made a Pythagorean Theorem calculator in Ruby and it has a bug/does not run. The error is:

undefined local variable or method `a2'

I was wondering if anyone could help.

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)}"
Это было полезно?

Решение

You just had two small errors:

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

Другие советы

Your Variables Are Undefined

You are confusing assignment with the equality operator (==). When you declare:

a**2 == a2

you are asking Ruby whether a2 is equal to the value of the a2 variable, which is undefined in your example code. You can see this same error at work if you open a new Ruby console and enter a2 without a program:

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>'

Some Refactoring

While you can fix your code by ensuring that you assign values to variables before you reference them, you should probably make your code more idiomatic. As an example, consider the following:

# 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)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top