-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つ、プログラムでは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 に答える