#!/usr/bin/env perl
use strict;
use warnings;
for(my $i=0; $i<100; $i++){
my $x = rand 100;
$x -= 50;
my $y =&roundToNearest($x,0.5);
print "$x > $y\n";
}
exit;
############################################################################
# Enables to round any real number to the nearest with a given precision even for negative numbers
# argument 1 : the float to round
# [argument 2 : the precision wanted]
#
# ie: precision=10 => 273 returns 270
# ie: no argument for precision means precision=1 (return signed integer) => -3.67 returns -4
# ie: precision=0.01 => 3.147278 returns 3.15
sub roundToNearest{
my $subname = (caller(0))[3];
my $float = $_[0];
my $precision=1;
($_[1]) && ($precision=$_[1]);
($float) || return($float); # no rounding needed for 0
#
my $rounded = int($float/$precision + 0.5*$float/abs($float))*$precision;
#
#print "$subname>precision:$precision float:$float > $rounded\n";
return($rounded);
}
以下是一个通用子程序,用于将给定精度四舍五入到最接近的值: 我举了一个你想要的四舍五入的例子,也就是0.5,我已经测试过了,即使使用负浮点数,它也能完美地工作
Perl解决方案:
简单的方法是:把数字除以2。在
相关问题 更多 >
编程相关推荐