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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。