網頁

2016年12月6日 星期二

UNIX入門課程1051_ex6

http://erdos.csie.ncnu.edu.tw/~klim/unix-intro/unix-intro-1051.html

作業六: figure out the average and the max three (sh programming)
寫一個 sh 的 program, 算出所有數字的平均及最大的三個數
數字從檔案讀入(若有給檔名的話), 或是從 keyboard 讀入(即 stdin, 若沒給檔名的話).
平均數要算到小數第二位.
若數字的個數小於三個, 則補 0.

$ cat k1
10 20 30
8 7
2
$ ./ex6.sh k1
the max three are: 30 20 10
the average is   : 12.83
$ cat k2
888 2
30
11 222
$ ./ex6.sh k1 k2
the max three are: 888 222 30
the average is   : 111.81
$ ./ex6.sh
1 2 3
4
5 6
the max three are: 6 5 4
the average is   : 3.50
$


解答:
#!/bin/bash
#calc average function
function AVERAGE () {
    avg=$(echo "scale=2; $1/$2" | bc )
    #echo "the average is   : $avg"
}
#bubble sort function
function SORT() {
    for ((i=0; i<count; i++))
    do
        for ((j=i; j<count; j++))
        do
            if [ ${data[j]} -gt ${data[i]} ]; then
                let temp=data[j]
                let data[j]=data[i]
                let data[i]=temp
            fi
        done
    done
}

if [ -z $1 ]; then  #manual input
  while read line
  do
    if [ "$line" != "" ]; then
      #set $(echo $line | tr : ' ')
      set $(echo $line)
      field=$#
      for ((i=1; i<=field; i++))
      do
        data[count]=$1
        let sum+=$1
        let count+=1
        shift
      done
    else
      break
    fi
  done<&0  
else  #file(s) input
  total_file=$#
  for ((i=1; i<=$total_file; i++)) #file name put in f[] array
  do
    f[i]=$1
    shift
  done
  for ((j=1; j<=$total_file; j++))
  do
    exec<"${f[j]}"
    while read line
    do
      set $(echo $line)
      field=$#
      for ((i=1; i<=field; i++))
      do
        data[count]=$1
        let sum+=$1
        let count+=1
        shift
      done
    done
  done #for END
fi
SORT #Run Bubble sort function
echo "the max three are: ${data[0]} ${data[1]} ${data[2]}"
AVERAGE $sum $count #Run calc average function
echo "the average is   : $avg"
執行結果:


 

沒有留言:

張貼留言