```Alle 16:58, venerd 5 gennaio 2007, Jay Bornhoft ha scritto:
> 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
>
> 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:
> # Date:   January 2006
> # Author: Jason Bornhoft
> # Email:  jbornhoft / gmail.com
>
> def sqr(a)
>   a * a
> end
>
>   (-b + (Math.sqrt( sqr(b) - 4*a*c ))) / 2*a
> end
>
>   (-b - (Math.sqrt( sqr(b) - 4*a*c ))) / 2*a
> end
>
> print "
> ---------------------------\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

Are you sure? I run your program with the values a=1, b=3 and c=1 and got the
correct results. Are you sure you didn't try with the coefficients of the
square of a bynomial (for instance a=1, b=2, c=1)?

As for checking the input, you can use a regexp:

input=gets.chomp
if !input.match /^\d+(.\d*)?\$/
puts "This is not a number"
exit
end

By the way, in ruby you can use operator ** to raise to a power, there's no
need to define the sqr method: use b**2.

There's also a better method to print the result:

puts "The formula is #{a} x^2 + #{b} x + #{c}\nand the values of x are: \n#{quad_pos(a,b,c)} and #{quad_neg(a,b,c)}"

Stefano

```