perl -Mbigrat -E'for (1..100) { $i += 1/3; say int($i), "\t", sprintf "%.55f", $i }'

垃圾邮件有很多警告:
Argument "100/3" isn't numeric in addition (+) at …/site_perl/5.24.1/Math/BigRat.pm line 1939.

在没有-Mbigrat的情况下再次运行,以查看sprintf的预期效果。

您如何将 Math::BigRat 实例$i降级为可转换为sprintf的普通NV

版本:
  • bigrat 0.47
  • Math::BigRat 0.2612
  • 最佳答案

    我期望Math::BigRat提供一种获取纯数字的方法,它可以:

  • 整数的as_int
  • float 的as_float

  • 我插入了$_的打印内容以进行调试。
    $i->as_int()int($i)相同:
    $ perl -Mbigrat -E'for (1..100) { $i += 1/3; say $_, "\t", int($i), "\t", sprintf "%.55f", $i->as_int() }'
    ...
    99      33      33.0000000000000000000000000000000000000000000000000000000
    100     33      33.0000000000000000000000000000000000000000000000000000000
    
    $i->as_float()乍一看似乎可以正常工作,但我不明白输出结果。所有小数位均为零,每第二行$i等于$_:
    $ perl -Mbigrat -E'for (1..100) { $i += 1/3; say $_, "\t", int($i), "\t", sprintf "%.55f", $i->as_float() }'
    ...
    90      30      30.0000000000000000000000000000000000000000000000000000000
    91      30      91.0000000000000000000000000000000000000000000000000000000
    92      30      92.0000000000000000000000000000000000000000000000000000000
    93      31      31.0000000000000000000000000000000000000000000000000000000
    94      31      94.0000000000000000000000000000000000000000000000000000000
    95      31      95.0000000000000000000000000000000000000000000000000000000
    96      32      32.0000000000000000000000000000000000000000000000000000000
    97      32      97.0000000000000000000000000000000000000000000000000000000
    98      32      98.0000000000000000000000000000000000000000000000000000000
    99      33      33.0000000000000000000000000000000000000000000000000000000
    100     33      100.0000000000000000000000000000000000000000000000000000000
    

    这是带有Math::BigRat 0.2614的Perl 5.30.0。

    因此,警告已修复,但此解决方案似乎出了点问题。

    更新:如无sprintf的注释中所要求:
    $ perl -Mbigrat -E'for (1..100) { $i += 1/3; say $_, "\t", int($i), "\t", $i->as_float() }'
    ...
    90      30      30
    91      30      91
    92      30      92
    93      31      31
    94      31      94
    95      31      95
    96      32      32
    97      32      97
    98      32      98
    99      33      33
    100     33      100
    

    10-04 11:26