Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
ax²+bx+c for newbies
Ytoba
4/25/2007 3:57:00 PM
Here is some very easy code to understand.
Since I started learning Ruby 2 years ago, I lacked examples.
So if this code can help newbies, the goal will be achieved.
Ytoba
include Math
require 'complex'
require 'rational'
begin
class Eq2
def initialize(a,b,c)
@a, @b, @c = Rational(a,1), Rational(b,1), Rational(c,1)
end
def to_s
ch = ""
ch += "#{@a}" unless @a == 1
ch += "-" if @a == -1
ch += "x²"
ch += "+" unless @b < 0
ch += "#{@b}" unless @b == 1
ch += "-" if @b == -1
ch += "x"
ch += "+" unless @c < 0
ch += "#{@c}" unless @c == 1
ch += "-" if @c == -1
ch
end
def delta
@b*@b - Rational(4,1)*@a*@c
end
def solve
dlt = delta
puts "delta=#{dlt}"
case
when dlt > 0
r1 = (-@b - sqrt(delta))/(2*@a).to_f
r2 = (-@b + sqrt(delta))/(2*@a).to_f
puts "Two distinct roots"
puts "r1=#{r1}"
puts "r2=#{r2}"
when dlt == 0
puts "A double root"
r= -@b/(2*@a)
puts "r=#{r}"
when dlt < 0
puts "delta=#{-delta}i²"
puts "Two complex roots"
r1 = Complex(-@b/(2*@a).to_f, -sqrt(-delta)/(2*@a).to_f)
r2 = Complex(-@b/(2*@a).to_f, sqrt(-delta)/(2*@a).to_f)
puts "r1=#{r1}"
puts "r2=#{r2}"
end
end
end
e = Eq2.new(1,-6,4)
puts e
e.solve
f = Eq2.new(1,2,5)
puts f
f.solve
end
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
ax²+bx+c for newbies
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password