Linux 编写一个Shall程序,键盘输入俩个数及+,-,*,/中的任意一个运算符,计算这俩数的运算结果。

如题所述

第1个回答  2011-11-09
#/bin/bash
i=$1
j=$2
c=$3

if [ $c == '+' ]
then
echo $i+$j="$((i+j))"
fi

if [ $c == '-' ]
then
echo $i-$j="$((i-j))"
fi
if [ $c == '*' ]
then
echo $i*$j="$((i*j))"
fi
if [ $c == '/' ]
then
echo $i/$j="$((i/j))"
fi
效果:
[root@ftp local]# ./test.sh 1 2 +
1+2=3
[root@ftp local]# ./test.sh 1 2 -
1-2=-1
第2个回答  2011-11-09
#!/bin/bash
first=$1
second=$2

case $3 in
+)
echo $(($first+$second));;
-)
echo $(($first-$second));;
*)
echo $(($first*$second));;
/)
echo $(($first/second));;
*)
exit;;
esac

root@ubuntu:~# ./calculate 3 4 *
12
root@ubuntu:~#
第3个回答  2011-11-09
#!/bin/bash
expr1=$1
expr2=$2
cal=$3

if [ $cal == a ]; then
cal='*'

fi

case $cal in
'+')
echo $(($expr1+$expr2));;
'-')
echo $(($expr1-$expr2));;
'*')
echo $(($expr1*$expr2));;
'/')
echo $(($expr1/$expr2));;
*)
echo 'please user this format: ./calc.sh expr1 expr2 {+ | - | * | / }'
esac

终于搞出来啦,之前一直被 * 这个乘号搞得错误,这次的代码终于可以正常了。
下面测试结果:
[root@rhel4 learn]# ./calc.sh 80 3 +
83
[root@rhel4 learn]# ./calc.sh 80 3 -
77
[root@rhel4 learn]# ./calc.sh 80 3 *
240
[root@rhel4 learn]# ./calc.sh 80 3 /
26
[root@rhel4 learn]# ./calc.sh 80 3 /ba
please user this format: ./calc.sh expr1 expr2 {+ | - | * | / }本回答被提问者采纳
相似回答