课程章节: 第2章 shell编程基础:2-8 Shell中的计算(课程链接:https://coding.imooc.com/lesson/549.html#mid=50184)
主讲老师: 沈奇才
课程内容:shell编程实战与Linux运维基础--初始shell编程
课程收获:
shell中的几种计算:
一)expr:用法如1+2:expr 1 + 2; expr 1 - 2 expr 1 \* 2 ;expr 1 / 2
二)let:
用法一、加减乘除运算:如1+2:let "1 += 2",(注意空格)
[zhang@localhost shell_with]$ a=1
[zhang@localhost shell_with]$ let "a += 2"
[zhang@localhost shell_with]$ echo $a
3
用法二、赋值:let "b=3+4+$a"
三)浮点型计算:bc命令
[zhang@localhost shell_with]$ bc
bc 1.06.95 ###bc的版本
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
1+2 ##计算开始
3 ##回车后的结果
---------echo中bc的使用:管道符加bc
[zhang@localhost shell_with]$ echo "1.2+1.1"
1.2+1.1
[zhang@localhost shell_with]$ echo "1.2+1.1"|bc
2.3
设置精度:scale,精度是2位小数:scale=2
[zhang@localhost shell_with]$ echo "scale=2;10/3"|bc
3.33
[zhang@localhost shell_with]$ echo "scale=3;10/3"|bc
3.333
实际操作中发现例外的情况:如果等号左边的数据精度超过规定的长度,则计算后的结果也会超过长度:
例1:echo输出:
[zhang@localhost shell_with]$ echo "scale=2;1.2222+1.1"|bc
2.3222 ##长度超过了规定的scale=2
例2:bc工具命令行:
[zhang@localhost shell_with]$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
sacle=3
3.33333+4.111111
7.444441
截图:
共同学习,写下你的评论
评论加载中...
作者其他优质文章