你正在用真實數字進行所有計算。您需要require 'complex'
才能獲得複數。我保留了你的程序結構 併爲其添加了複數。
另一件事,在你的程序中你有1/2,但因爲它們是整數,所以這個除法結果爲0,因爲整數除法將小數結果丟掉(例如7/2是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)
嗨,歡迎來到stackoverflow!你能指定這是什麼語言(帶標籤)嗎?請妥善格式化代碼!謝謝 – codeling
這是我如何格式化它,我不知道我會怎麼做,否則!我是新來的,並通過紅寶石(我的mac上的終端)運行它 – user1650578