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所需的效果。
如何将BigRat实例$ i降级为sprintf的普通NV?
版本:
答案 0 :(得分:1)
我希望Math::BigRat
提供一种获取纯数字的方法,并且可以:
as_int
表示整数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
答案 1 :(得分:0)
不是那么认真的答案:
use bigrat;
use feature 'say';
for (1..100) {
$i += 1/3;
no bigrat;
say int($i),"\t",sprintf "%.55f", eval "$i"
}