当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。