-2

这是我的二次计算器的代码:

puts "A?"
a = gets.to_f
puts "B?"
b = gets.to_f
puts "C?"
c = gets.to_f

d = (-b + (((b**2) - (4*a*c))**(1/2)))/(2*a)
puts d

f = (-b - (((b**2) - (4*a*c))**(1/2)))/(2*a)
puts f

然而,答案并不总是正确的。

例如,我没有得到虚数。

我究竟做错了什么?

4

1 回答 1

1

您正在使用实数进行所有计算。你需要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)
于 2012-09-13T00:44:54.220 回答