2012-09-11 88 views
-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 

然而,答案並不總是正確的。

例如,我沒有得到虛數。

我在做什麼錯?

+1

嗨,歡迎來到stackoverflow!你能指定這是什麼語言(帶標籤)嗎?請妥善格式化代碼!謝謝 – codeling

+0

這是我如何格式化它,我不知道我會怎麼做,否則!我是新來的,並通過紅寶石(我的mac上的終端)運行它 – user1650578

回答

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) 
+0

歡迎來到StackOverflow。如果您發現此答案正確,請選擇左側數字下方的「複選標記」,然後選擇數字上方的向上箭頭來增加計數。謝謝。 – vacawama