Rescuing a DivisionByZero with default value returns NaN in ruby?
我希望开始救援将比率设置为零,但是它设置为
1 2 3 4 5 6 7 | ratio = begin 0.0 / 0.0 rescue ZeroDivisionError 0 end ratio = 0 if ratio.nan? |
我想摆脱的代码是
编辑
新代码看起来像:
1 2 | ratio = bet_money_amount_cents.to_f / total_amount.to_f ratio.nan? ? 0 : ratio |
因为
尝试将整数除以0时,
1 2 | 42 / 0 #=> ZeroDivisionError: divided by 0 |
请注意,只有精确
1 2 3 | 42 / 0.0 #=> Float::INFINITY 42 / -0.0 #=> -Float::INFINITY 0 / 0.0 #=> NaN |
我会写如下:
1 2 | ratio = bet_money_amount_cents.to_f / total_amount.to_f ratio = 0 if ratio.nan? |
因为
1 2 3 4 5 6 7 8 9 | 0.0 / 0.0 # => NaN 0.0 / 0 # => NaN 0 / 0 # ZeroDivisionError: divided by 0 # from (irb):17:in `/' # from (irb):17 # from C:/Ruby200-x64/bin/irb:12:in `<main>' |
根据
Raised when attempting to divide an integer by 0.
您可以简化代码:
1 | ratio = total_amount == 0 ? 0 : bet_money_amount_cents.to_f / total_amount |