我需要得到最接近的数字$new来$orig整除$divisor。该$new应大于$orig。所以我提出了以下公式(希望没有错误):
$new = $orig + ($divisor - $orig % $divisor)
Run Code Online (Sandbox Code Playgroud)
现在,这个$orig数字是一个整数,最多有 30 位数字。我想使用 将其实现到 Perl 函数中Math::BigInt,但输出非常错误。
$new = $orig + ($divisor - $orig % $divisor)
Run Code Online (Sandbox Code Playgroud)
https://metacpan.org/pod/Math::BigInt#Arithmetic-methods:“这些方法修改调用对象并返回它。” 换句话说,bmod, bsub, andbadd类似于%=, -=, and +=,而不是%, -, and +。
因此,无论在何处调用一种算术方法,都应该先复制,这样当前调用该方法的对象不会更改:
use Math::BigInt;
Math::BigInt->accuracy(60);
Math::BigInt->precision(60);
my $orig = Math::BigInt->new('5967920747812842369477355441'); # A
my $divisor = Math::BigInt->new('719'); # B
my $modulo = $orig->copy->bmod($divisor); # A % B = M
my $diff = $divisor->copy->bsub($modulo); # B - M = D
my $new = $orig->copy->badd($diff); # A + D = N
my $test = $new->copy->bmod($divisor); # N % B = 0
print("orig : $orig\n"); # 10; should be: 5967920747812842369477355441
print("modulo : $modulo\n"); # 10; should be: 648
print("diff : $diff\n"); # 71; should be: 71
print("new : $new\n"); # 10; should be: 5967920747812842369477355512
print("test : $test\n"); # 10; should be: 0
Run Code Online (Sandbox Code Playgroud)
(还更改了您的测试以进行模数,而不是除法。)