本帖最后由 喵呜喵5 于 2015-9-12 15:48 编辑
class Fraction attr_accessor :numerator, :denominator def initialize(array) @numerator = array[0].to_i @denominator = array[1].to_i raise "分母不为0" if @denominator == 0 reduction end # 极其简陋的约分(破坏性) def reduction @denominator = 1 if @numerator == 0 [@denominator, @numerator, 2, 3, 5, 7].each do |i| next if i == 1 || i == -1 || i == 0 while @numerator % i == 0 && @denominator % i == 0 @denominator /= i; @numerator /= i end end self end # 取负数(破坏性) def -@; self.numerator = -self.numerator; self; end # 取倒数(破坏性) def reciprocal self.numerator ,self.denominator = self.denominator, self.numerator self end # 将整数转换为分数 def change_to_fraction(number) return Fraction.new([number,1]) if number.class != Fraction number end # 加 def +(number) r = self.clone n = change_to_fraction(number) r.numerator *= n.denominator r.numerator += n.numerator * r.denominator r.denominator *= n.denominator r.reduction end # 乘 def *(number) n = change_to_fraction(number) r = self.clone r.denominator *= n.denominator r.numerator *= n.numerator r.reduction end # 减 def -(number); self.+(-number); end # 除 def /(number); self.*(change_to_fraction(number).reciprocal); end # 数据类型的转换 def to_f; @numerator.to_f / @denominator; end def to_i; @numerator / @denominator; end def to_s return @numerator.to_s if @denominator == 1 "#{@numerator}/#{@denominator}" end end a = Fraction.new([1,4]) b = Fraction.new([2,3]) p a + b p a - 1 p b * 3 p b / a
class Fraction
attr_accessor :numerator, :denominator
def initialize(array)
@numerator = array[0].to_i
@denominator = array[1].to_i
raise "分母不为0" if @denominator == 0
reduction
end
# 极其简陋的约分(破坏性)
def reduction
@denominator = 1 if @numerator == 0
[@denominator, @numerator, 2, 3, 5, 7].each do |i|
next if i == 1 || i == -1 || i == 0
while @numerator % i == 0 && @denominator % i == 0
@denominator /= i; @numerator /= i
end
end
self
end
# 取负数(破坏性)
def -@; self.numerator = -self.numerator; self; end
# 取倒数(破坏性)
def reciprocal
self.numerator ,self.denominator = self.denominator, self.numerator
self
end
# 将整数转换为分数
def change_to_fraction(number)
return Fraction.new([number,1]) if number.class != Fraction
number
end
# 加
def +(number)
r = self.clone
n = change_to_fraction(number)
r.numerator *= n.denominator
r.numerator += n.numerator * r.denominator
r.denominator *= n.denominator
r.reduction
end
# 乘
def *(number)
n = change_to_fraction(number)
r = self.clone
r.denominator *= n.denominator
r.numerator *= n.numerator
r.reduction
end
# 减
def -(number); self.+(-number); end
# 除
def /(number); self.*(change_to_fraction(number).reciprocal); end
# 数据类型的转换
def to_f; @numerator.to_f / @denominator; end
def to_i; @numerator / @denominator; end
def to_s
return @numerator.to_s if @denominator == 1
"#{@numerator}/#{@denominator}"
end
end
a = Fraction.new([1,4])
b = Fraction.new([2,3])
p a + b
p a - 1
p b * 3
p b / a
|