I wrote a small program to solve for x using the quadratic formula but
instead of receiving a + and - result I am getting two identical
answers…
Is the problem with my math or with my code?
Also, how can I require the input to be a valid rational number?
Thanks
Code:
Name: quadratic-jb.rb
Date: January 2006
Author: Jason B.
Email: [email protected]
def sqr(a)
a * a
end
def quad_pos(a, b, c)
(-b + (Math.sqrt( sqr(b) - 4ac ))) / 2*a
end
def quad_neg(a, b, c)
(-b - (Math.sqrt( sqr(b) - 4ac ))) / 2*a
end
print "
Solving Quadratic Equations
---------------------------\n"
puts "Enter the value of a: "
a = gets.chomp.to_f
puts "Enter the value of b: "
b = gets.chomp.to_f
puts " Enter the value of c: "
c = gets.chomp.to_f
puts "The formula is " + a.to_s + "x^2 + " + b.to_s + "x + " + c.to_s
puts “and the values of x are:”
puts quad_pos(a, b, c).to_s + " and " + quad_neg(a, b, c).to_s