📅  最后修改于: 2023-12-03 14:56:48.549000             🧑  作者: Mango
有理截断() 函数是红宝石(Ruby)语言中的一个内置方法,用于将浮点数转换为有理数,并将其约分至最简形式。
irb(main):001:0> number.rationalize(epsilon = Float::EPSILON) => rational
epsilon
:确定有理数近似值的阈值。默认值为 Float::EPSILON
。返回有理数对象 rational
。
irb(main):001:0> 1.5.rationalize
=> (3/2)
irb(main):001:0> 0.3.rationalize(0.001)
=> (3/10)
irb(main):001:0> 0.3.rationalize
=> (3/10)
irb(main):002:0> Rational(0.3)
=> (5404319552844595/18014398509481984)
def fraction_to_decimal(numerator, denominator)
numerator = numerator.to_i
denominator = denominator.to_i
if numerator % denominator == 0
numerator / denominator
else
gcd = numerator.gcd(denominator)
if gcd != 1
numerator = numerator / gcd
denominator = denominator / gcd
end
"#{numerator}/#{denominator}"
end
end
irb(main):001:0> rational = 0.3.rationalize
=> (3/10)
irb(main):002:0> fraction_to_decimal(rational.numerator, rational.denominator)
=> "3/10"
使用过程中需要注意以下事项: