如何在Raku中指定序列显式生成器的输出小数位数?
在Raku中控制序列输出的小数位数
你的原始代码及输出如下:
sub euler-ex ($x) of Seq { 1, { $x**++$ / [×] 1 .. ++$ } ... Inf } say " 5: " ~ euler-ex(5)[^20] ~ " = " ~ [+](euler-ex(5)[^20]);
输出:
5: 1 5 12.5 20.833333 26.041667 26.041667 21.701389 15.500992 9.68812 5.382289 2.6911445 1.22324748 0.50968645 0.19603325 0.07001187499 0.023337291662 0.0072929036444 0.00214497166011 0.000595825461143 0.000156796173985 = 148.41310786833832
要指定输出的小数位数,你可以利用Raku的字符串格式化功能,对序列元素和求和结果统一处理,具体有两种常用方式:
方法一:使用sprintf函数
通过sprintf的格式化字符串控制小数位数,比如%.4f表示保留4位小数。修改代码如下:
sub euler-ex ($x) of Seq { 1, { $x**++$ / [×] 1 .. ++$ } ... Inf } # 定义要保留的小数位数 my $decimal-digits = 4; # 获取序列前20项 my @terms = euler-ex(5)[^20]; # 格式化每个序列元素 my $formatted-terms = @terms.map: -> $t { sprintf "%.${decimal-digits}f", $t }; # 计算总和并格式化 my $total = [+] @terms; my $formatted-total = sprintf "%.${decimal-digits}f", $total; say " 5: " ~ $formatted-terms.join(' ') ~ " = " ~ $formatted-total;
方法二:使用Raku原生的.fmt方法
Raku的数值类型自带.fmt方法,用法和sprintf类似,代码更简洁:
sub euler-ex ($x) of Seq { 1, { $x**++$ / [×] 1 .. ++$ } ... Inf } my $decimal-digits = 4; my @terms = euler-ex(5)[^20]; my $formatted-terms = @terms.map: *.fmt("%.${decimal-digits}f"); my $formatted-total = ([+] @terms).fmt("%.${decimal-digits}f"); say " 5: " ~ $formatted-terms.join(' ') ~ " = " ~ $formatted-total;
示例输出(保留4位小数)
5: 1.0000 5.0000 12.5000 20.8333 26.0417 26.0417 21.7014 15.5010 9.6881 5.3823 2.6911 1.2232 0.5097 0.1960 0.0700 0.0233 0.0073 0.0021 0.0006 0.0002 = 148.4131
你只需要修改$decimal-digits的值,就能轻松调整输出的小数位数。
内容的提问来源于stack exchange,提问作者Lars Malmsteen
相关产品推荐
相关产品推荐

