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


Perl abs()用法及代碼示例


此函數返回其參數的絕對值。如果傳遞了純整數值,則它將按原樣返回它,但是如果傳遞了字符串,則它將返回零。如果省略VALUE,則使用$_

用法: abs(VALUE)

參數:
VALUE:這是必需的數字,可以是正數或負數或字符串。


返回:函數返回傳遞的參數的絕對值。

範例1:

#!/usr/bin/perl 
  
# Defining decimal value 
$var1 = 15.8; 
  
# Defining integer value 
$var2 = 7; 
  
# Defining negative value 
$var3 = "-15.2"; 
  
# Calling abs() function 
$res1 = abs($var1); 
$res2 = abs($var2); 
$res3 = abs($var3); 
  
# Printing these values 
print "Abs value of var1 is $res1\n"; 
print "Abs value of var2 is $res2\n"; 
print "Abs value of var3 is $res3";

輸出:

Abs value of var1 is 15.8
Abs value of var2 is 7
Abs value of var3 is 15.2

範例2:

#!/usr/bin/perl 
  
# Defining string value 
$var1 = "Geeks"; 
  
# Defining Fractional value 
$var2 = 7/2; 
  
# Calling abs() function 
$res1 = abs($var1); 
$res2 = abs($var2); 
  
# Print these values 
print "Abs value of var1 is $res1\n"; 
print "Abs value of var2 is $res2";

輸出:

Abs value of var1 is 0
Abs value of var2 is 3.5


相關用法


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