perl中的数学运算


perl中以双精度(浮点数)保存和进行数值运算,就算写的是整数,在内部也会转换成等效的浮点数类型保存;但在perl内部,有些运算会将浮点数转换成整型进行,而且也有integer编译指令可以强制编译成整型。perl中整数有3种表示方式:
123
0123
61_123_234
这里使用下划线(_)代替逗号表示千分位,因为perl中逗号有特殊意义。
算术运算
+ - * / % **
**的优先级在这里最高。
取模时,先两个数取整,再取模。例如5.2%2.1等价于5%2。
多个取幂符号时,**的优先级是从右向左进行的。
3 ** 4 ** 2 # 3 ** (4 ** 2) = 3的16次方
需要对数字进行数学做的运算有:四舍五入、取整、取最小等。
Ceil
Cieling is basically outputing the next largest integer for an given real number.
返回比给出数字最近的且比它大整数。
ceiling(x) is the smallest integer not less than x. Ways to do it in Perl:
a)using our own logic
my $num=45.4;
my $ceil=int($num+0.99);
b)using POSIX
use POSIX qw/ceil/;
my $num=45.4;
my $ceil=ceil($num);
Floor
Flooring is outputing the next smallest integer for an given real number.
返回比给出数字最近的且比它小的整数。
floor(x) is the largest integer not greater than x.Ways to do it in Perl:
a)using our own logic
my $num=45.4;
my $floor=int($num);
b)using POSIX
use POSIX qw/floor/;
my $num=45.4;
my $floor=floor($num);
Round
Rounding is converting any floating-point number to the nearest integer.
它就是日常所说的四舍五入了。
Ways to do it in Perl:
a)using our own logic
my $num=45.4;
my $round=int($num + 0.5);
b)using Math::Round
use Math::Round qw/round/;
my $num=45.4;
my $round=round($num);
It'll be really nice if everyone crontributes to this thread with the equivalent functions in the language they are comfortable with.
123
0123
61_123_234
这里使用下划线(_)代替逗号表示千分位,因为perl中逗号有特殊意义。
算术运算
+ - * / % **
**的优先级在这里最高。
取模时,先两个数取整,再取模。例如5.2%2.1等价于5%2。
多个取幂符号时,**的优先级是从右向左进行的。
3 ** 4 ** 2 # 3 ** (4 ** 2) = 3的16次方
需要对数字进行数学做的运算有:四舍五入、取整、取最小等。
Ceil
Cieling is basically outputing the next largest integer for an given real number.
返回比给出数字最近的且比它大整数。
ceiling(x) is the smallest integer not less than x. Ways to do it in Perl:
a)using our own logic
my $num=45.4;
my $ceil=int($num+0.99);
b)using POSIX
use POSIX qw/ceil/;
my $num=45.4;
my $ceil=ceil($num);
Floor
Flooring is outputing the next smallest integer for an given real number.
返回比给出数字最近的且比它小的整数。
floor(x) is the largest integer not greater than x.Ways to do it in Perl:
a)using our own logic
my $num=45.4;
my $floor=int($num);
b)using POSIX
use POSIX qw/floor/;
my $num=45.4;
my $floor=floor($num);
Round
Rounding is converting any floating-point number to the nearest integer.
它就是日常所说的四舍五入了。
Ways to do it in Perl:
a)using our own logic
my $num=45.4;
my $round=int($num + 0.5);
b)using Math::Round
use Math::Round qw/round/;
my $num=45.4;
my $round=round($num);
It'll be really nice if everyone crontributes to this thread with the equivalent functions in the language they are comfortable with.