You were doing all of your calculations with real numbers. You need to require 'complex'
to get complex numbers. I kept your program structure
and added complex numbers to it.
One other thing, in your program you had 1/2 but since these are integers, this division results in 0 since integer division throws away the fractional result (eg. 7/2 is 3).
#!/usr/bin/ruby
require 'complex'
# very small real number, consider anything smaller than this to
# be zero
EPSILON = 1e-12
def print_complex(n)
# break n into real and imaginary parts
real = n.real
imag = n.imag
# convert really small numbers to zero
real = 0.0 if real.abs < EPSILON
imag = 0.0 if imag.abs < EPSILON
# if the imaginary part is zero, print as a real
if n.imag == 0.0
puts real
else
puts Complex(real, imag)
end
end
puts "A?"
a = gets.to_f
puts "B?"
b = gets.to_f
puts "C?"
c = gets.to_f
# Turn the real numbers into complex numbers
ac = Complex(a, 0)
bc = Complex(b, 0)
cc = Complex(c, 0)
dc = (-bc + (((bc**2) - (4*ac*cc))**(1.0/2)))/(2*ac)
print_complex(dc)
fc = (-bc - (((bc**2) - (4*ac*cc))**(1.0/2)))/(2*ac)
print_complex(fc)