首页 > 运营 > 帮助中心 > 正文

Shell脚本编程中常用的数学运算实例

2020-07-28 14:07:29
字体:
来源:转载
供稿:网友

这部分主要讨论数学相关的shell脚本编程。

加法运算

新建一个文件“Addition.sh”,输入下面的内容并赋予其可执行的权限。
复制代码 代码如下:#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
x=$(expr "$a" + "$b")
echo $a + $b = $x
输出结果:
复制代码 代码如下:
[root@tecmint ~]# vi Additions.sh
[root@tecmint ~]# chmod 755 Additions.sh
[root@tecmint ~]# ./Additions.sh
 
“Enter the First Number: ”
12
“Enter the Second Number: ”
13
12 + 13 = 25

减法运算

复制代码 代码如下:
#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
x=$(($a - $b))
echo $a - $b = $x
注意:这里我们没有像上面的例子中使用“expr”来执行数学运算。

输出结果:
复制代码 代码如下:
[root@tecmint ~]# vi Substraction.sh
[root@tecmint ~]# chmod 755 Substraction.sh
[root@tecmint ~]# ./Substraction.sh
 
“Enter the First Number: ”
13
“Enter the Second Number: ”
20
13 - 20 = -7

乘法运算
复制代码 代码如下:
#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
echo "$a * $b = $(expr $a /* $b)"
输出结果:
复制代码 代码如下:
[root@tecmint ~]# vi Multiplication.sh
[root@tecmint ~]# chmod 755 Multiplication.sh
[root@tecmint ~]# ./Multiplication.sh
 
“Enter the First Number: ”
11
“Enter the Second Number: ”
11
11 * 11 = 12

除法运算
复制代码 代码如下:
#!/bin/bash
echo “Enter the First Number: ”
read a
echo “Enter the Second Number: ”
read b
echo "$a / $b = $(expr $a / $b)"
输出结果:
复制代码 代码如下:
[root@tecmint ~]# vi Division.sh
[root@tecmint ~]# chmod 755 Division.sh
[root@tecmint ~]# ./Division.sh
 
“Enter the First Number: ”
12
“Enter the Second Number: ”
3
12 / 3 = 4

数组

下面的这个脚本可以打印一组数字。
复制代码 代码如下:
#!/bin/bash
echo “Enter The Number upto which you want to Print Table: ”
read n
i=1
while [ $i -ne 10 ]
do
i=$(expr $i + 1)
table=$(expr $i /* $n)
echo $table
done
输出结果:
复制代码 代码如下:
[root@tecmint ~]# vi Table.sh
[root@tecmint ~]# chmod 755 Table.sh
[root@tecmint ~]# ./Table.sh
 
“Enter The Number upto which you want to Print Table: ”
29
58
87
116
145
174
203
232
261
290
你可以从这里下载这个例子的代码

判断奇偶数

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表