在Linux系统下,编写一个Shell脚本,从键盘读入5个整数,然后显示最大数、最小数、和平均数。

2024年11月14日 13:37
有4个网友回答
网友(1):

#!/bin/bash

#任意输入5个数,判断最大值,最小值,总和

s=0

read -p "please input:" num

s=$(($s+$num))

max=$num

min=$num

avg=$(($s/5))

for i in `seq 4`

do

      read -p "please input:" num
s=$(($s+$num))

      if [ $num -le $min ];then
min=$num
fi

      if [ $num -ge $max ];then
max=$num
fi

done

echo max:$max min:$min avg:$avg

扩展资料:

for循环:

一般格式为:

for var in item1 item2 ... itemN

do

    command1

    command2

    ...

    commandN

done

写成一行:

for var in item1 item2 ... itemN; do command1; command2… done;

网友(2):

楼上的程序我执行到第“5”行那就出错了,更别说结果了;我专门写了简单易懂的,程序如下:
#!/bin/bash
echo " Please input 5 word "
echo -n " word 1: "
read word1
echo -n " word 2: "
read word2
echo -n " word 3: "
read word3
echo -n " word 4: "
read word4
echo -n " word 5: "
read word5

if [ "$word1" -ge "$word2" -a "$word1" -ge "$word3" -a "$word1" -ge "$word4" -a "$word1" -ge "$word5" ]
then
echo -n " Max: $word1"
elif [ "$word2" -ge "$word1" -a "$word2" -ge "$word3" -a "$word2" -ge "$word4" -a "$word2" -ge "$word5" ]
then
echo -n " Max: $word2"
elif [ "$word3" -ge "$word2" -a "$word3" -ge "$word1" -a "$word3" -ge "$word4" -a "$word3" -ge "$word5" ]
then
echo -n " Max: $word3"
elif [ "$word4" -ge "$word2" -a "$word4" -ge "$word3" -a "$word4" -ge "$word1" -a "$word4" -ge "$word5" ]
then
echo -n " Max: $word4"
else
echo -n " Max: $word5"
fi

if [ "$word1" -le "$word2" -a "$word1" -le "$word3" -a "$word1" -le "$word4" -a "$word1" -le "$word5" ]
then
echo -n " Min: $word1"
elif [ "$word2" -le "$word1" -a "$word2" -le "$word3" -a "$word2" -le "$word4" -a "$word2" -le "$word5" ]
then
echo -n " Min: $word2"
elif [ "$word3" -le "$word2" -a "$word3" -le "$word1" -a "$word3" -le "$word4" -a "$word3" -le "$word5" ]
then
echo -n " Min: $word3"
elif [ "$word4" -le "$word2" -a "$word4" -le "$word3" -a "$word4" -le "$word1" -a "$word4" -le "$word5" ]
then
echo -n " Min: $word4"
else
echo -n " Min: $word5"
fi

echo " Ave: expr '($word1 \+ $word2 \+ $word3 \+ $word4 \+ $word5)\/5'"
本程序在我电脑是可以执行出结果的,要是在你的系统执行出错,请告知我。谢谢。

网友(3):

1 #!/bin/bash
2 echo "**********please iput 5 number***********************"
3 echo "you must input one and press enter until input 5 number"
4 read x
5 max=$x
6 min=$x
7 avg=$x
8 i=1
9 while [ $i -lt "5" ]
10 do
11 let "i+=1"
12 read x
13 if [ "$x" -gt "$max" ]
14 then max=$x
15 fi
16 if [ "$x" -le "$min" ]
17 then min=$x
18
19 fi
20 let "avg=$avg+$x"
21 done
22 avg=$(echo "scale=3;$avg/5"|bc -l) #scale控制平均数的精度
23 echo "***********the result***************"
24 echo "max=$max "
25 echo "min=$min "
26 echo "avg=$avg"

网友(4):

  
#!/bin/bash
read num
max=$num
min=$num
for((i<1;i<10;i++))
do
read num
if test $max -le $num
then
max=$num
fi
if test $min -ge $num
then
min=$num
fi
done
echo "max=$max,min=$min"