當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


perl Math::BigInt->digit()用法及代碼示例


Math::BigIntPerl中的module提供了代表具有任意精度的整數和重載算術運算符的對象。

digit()的方法Math::BigInt模塊用於獲取從右開始計數的給定數字的第n個數字。要從左側獲取數字,我們需要將n指定為負數。

用法: Math::BigInt->digit($n)

參數:
$n:表示要提取的數字的整數值。

返回:一個整數值,代表從右側開始計數的給定數字的第n個數字。

範例1:用於Math::BigInt->digit()方法

#!/usr/bin/perl  
  
# Import Math::BigInt module 
use Math::BigInt; 
  
$num = 7821593604; 
  
# Create a BigInt object 
$x = Math::BigInt->new($num); 
  
# Initialize n 
$n = 4; 
  
# Get the nth digit 
# counting from right side  
$nth_digit = $x->digit($n); 
  
print "${n}th digit in $num is $nth_digit.\n"; 
  
# Assign new value to n 
$n = 6; 
  
# Get the nth digit  
# counting from right side 
$nth_digit = $x->digit($n); 
  
print "${n}th digit in $num is $nth_digit.\n";
輸出:
4th digit in 7821593604 is 9.
6th digit in 7821593604 is 1.

範例2:用於Math::BigInt->digit()從左邊獲取第n個數字的方法

#!/usr/bin/perl  
  
# Import Math::BigInt module 
use Math::BigInt; 
  
$num = 7821593604; 
  
# Create a BigInt object 
$x = Math::BigInt->new($num); 
  
# To get nth digit form  
# left side of the number 
# we need to specify n  
# as a negative number  
  
# If n is negative then  
# then method will return 
# nth digit from left side 
# but counting will start from 1. 
  
# Initialize n 
$n = 4; 
  
# Get the nth digit 
# from left side  
$nth_digit = $x->digit(-$n); 
  
print "${n}th digit from left in $num is $nth_digit.\n"; 
  
# Assign new value to n 
$n = 6; 
  
# Get the nth digit  
# counting from left side 
$nth_digit = $x->digit(-$n); 
  
print "${n}th digit from left in $num is $nth_digit.\n";
輸出:
4th digit from left in 7821593604 is 1.
6th digit from left in 7821593604 is 9.

範例3:用於Math::BigInt->digit()計算一個數字的位數的方法

#!/usr/bin/perl  
  
# Import Math::BigInt module 
use Math::BigInt; 
  
$num = 7821593604; 
  
# Create a BigInt object 
$x = Math::BigInt->new($num); 
  
# Get the length of the number 
$length = $x->length(); 
  
# Variable to store sum 
$sum = 0; 
  
# for loop to calculate  
# sum of digits in given number 
for($i = 0; $i < $length; $i++) 
{ 
    # Get the ith digit from the 
    # right side of the number  
    $sum = $sum + $x->digit($i); 
  
} 
  
# Print sum 
print "Sum of digits in $num is $sum.";
輸出:
Sum of digits in 7821593604 is 45.


相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Perl | Math::BigInt->digit() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。