Math::BigInt
Perl中的module提供了代表具有任意精度的整数和重载算术运算符的对象。
length()
Math::BigInt模块的方法用于获取给定数字的长度,即给定数字中的位数。
用法: Math::BigInt->length()
参数:没有
返回:一个整数值,代表给定数字的长度。
范例1:用于Math::BigInt->length()
计算数字位数的方法
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
# Specify number
$num = 78215936043546;
# Create BigInt object
$x = Math::BigInt->new($num);
# Get the length (or count of
# digits) of the
# given number using
# Math::BigInt->length() method
$len = $x->length();
print "Length of $num is $len.\n";
# Specify another number
$num = 7821593604584625197;
# Create BigInt object
$x = Math::BigInt->new($num);
# Get the length (or count of
# digits) of the
# given number using
# Math::BigInt->length() method
$len = $x->length();
print "Length of $num is $len.\n";
输出:
Length of 78215936043546 is 14. Length of 7821593604584625197 is 19.
范例2:用于Math::BigInt->length()
将给定数字分为两半的方法。
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
# Specify number
$num = 78215936043546;
# Create BigInt object
$x = Math::BigInt->new($num);
# Get the length (or count of
# digits) of the
# given number using
# Math::BigInt->length() method
$len = $x->length();
# Variable to store first half
$firstHalf = 0;
$i = 1;
# loop to calculate first half
while($i <= ($len/2))
{
$firstHalf = ($firstHalf * 10) +
$x->digit(-$i);
$i = $i + 1;
}
# Variable to store second half
$secondHalf = 0;
# Loop to calculate second half
while($i <= $x->length())
{
$secondHalf = ($secondHalf * 10) +
$x->digit(-$i);
$i = $i + 1;
}
# Note:Math::BigInt->digit() method
# returns the digit at ith position
# from right end of the given number
# a negative value of i is used
# to get ith digit from left end
# of the given number
# Print original number
print "Original number:$num\n";
# Print first half
print "First half:$firstHalf\n";
# Print Second half
print "Second half:$secondHalf";
输出:
Original number:78215936043546 First half:7821593 Second half:6043546
相关用法
- perl Math::BigInt->bone()用法及代码示例
- perl Math::BigInt->from_oct()用法及代码示例
- perl Math::BigInt->from_hex()用法及代码示例
- perl Math::BigInt->binf()用法及代码示例
- perl Math::BigInt->bneg()用法及代码示例
- perl Math::BigInt->from_bin()用法及代码示例
- perl Math::BigInt->bnan()用法及代码示例
- perl Math::BigInt->is_odd()用法及代码示例
- perl Math::BigInt->config()用法及代码示例
- perl Math::BigInt->digit()用法及代码示例
- perl Math::BigInt->brsft()用法及代码示例
- perl Math::BigInt->bfac()用法及代码示例
注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Perl | Math::BigInt->length() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。