bash数学运算之bc

一、expr

1.1 语法

注意必须有空格

只能精确到整数,无法精确到浮点数

image

1.2 操作符对照表

image

使用expr命令时需要加\进行转义,因为部分符号是保留关键字

image

例1:比较num1跟num2的大小

[root@localhost ~]# num1=30
[root@localhost ~]# num2=50
[root@localhost ~]# expr $num1 \> $num2
0
[root@localhost ~]# num3=`expr $num1 \> $num2`

其余以此类推

例2:使用$(())求积

注意*会自动转义,不需要转义符号

不能进行等于,不等于运算,所以比较运算建议使用expr命令

扫描二维码关注公众号,回复: 9021407 查看本文章
[root@localhost ~]# num1=30
[root@localhost ~]# num2=20
[root@localhost ~]# echo $(($num1*$num2))
600

练习题

要求:提示用户输入一个正整数num,计算1+2+3+…+num的值。

需要判断是否为整数

[root@localhost ~]# num1=56.1
[root@localhost ~]# expr $num1 + 1
expr: 非整数参数
[root@localhost ~]# echo $?
2
#可以看到报错,输出结果为2
[root@localhost ~]# num1=56
[root@localhost ~]# expr $num1 + 1
57
[root@localhost ~]# echo $?
0
#输出结果为0表示执行成功

答案

[root@localhost ShellScript]# cat example_4.sh
#!/bin/bash
while true
do
read -p "pls input a positive number:" num
expr $num + 1 &> /dev/null
if [ $? -eq 0 ];then
        if [ `expr $num \> 0` -eq 1 ];then
                for((i=1;i<=$num;i++))
                do
                        sum=`expr $sum + $i`
                done
                echo "1+2+3+...+$num=$sum"
                exit
        fi
fi
echo "error,input enlegal"
done
答案

二、bc

2.1 语法

bc是bash自带的运算器,支持浮点数运算

如果不指定scale变量,默认还是得到的整数

自带变量scale可以设置,默认为0,也就是为整型

支持+,-,*,/,%,^运算

num1 + num2
num1 - num2
num1 * num2
num1 / num2
num1 % num2
num1 ^ num2  //指数运算

2.2 例子

输入bc回车进入互动模式

[root@localhost ShellScript]# 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'.
5+5
10
5/3
1
scale=2  //保留小数点后两位
23/5
4.60

或者

[root@localhost ShellScript]# echo "12+45" | bc
57

通过scale设置精确度

[root@localhost ShellScript]# echo "scale=4;12.56*45.88" | bc
576.2528

简易到爆的乘法计算器

[root@localhost ShellScript]# cat bc.sh
#!/bin/bash

read -p "num1:" num1
read -p "num2:" num2
echo "scale=4;$num1*$num2" | bc
或者
num3=`echo "scale=4;$num1*$num2" | bc`
echo $num3

猜你喜欢

转载自www.cnblogs.com/tz90/p/12285655.html