如何编程二次计算器?

时间:2012-09-11 12:44:27

标签: ruby calculator quadratic

以下是我的二次计算器的代码:

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

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

例如,我没有想象中的数字。

我做错了什么?

1 个答案:

答案 0 :(得分: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)