Demo entry 6630332

shell

   

Submitted by anonymous on Jul 09, 2017 at 15:44
Language: Bash. Code size: 902 Bytes.

# title : num_anaysis.sh
# author: Yuxuan Yang  3140104328
#function: 从键盘输入的100个整数,计算其平均值、最大值和最小值并输出,从小到大排序并输出。

#!/bin/bash

declare -a num[100] #声明数组

if [[ $# = 0 ]]; then  #没有参数传入
	echo "input numbers"
	read -a num
else		#有参数传入,则将参数存入数组
	i=0
	for n in "$@"; do
		num[i]=$n
		#echo "num[$i]=${num[i]}"
		i=$((i+1))
	done
fi
if test -n ${num[0]} #数组非空
	then
	sum=0  # 初始化数据和
else
	echo "data not found" #没有数据则报错退出
	exit 1
fi

len=${#num[@]}   #数据个数
 
for((i=0; i<$len; i++)){ #排序顺便计算总和
  for((j=i+1; j<$len; j++)){
 
    if [[ ${num[i]} -gt ${num[j]} ]] #i>j
    then
      temp=${num[i]}  #交换i和j
      num[i]=${num[j]}
      num[j]=$temp
    fi
 
  }
  sum=$((sum+num[i]))	#更新sum值
}
min=${num[0]}	#最小值
max=${num[$((len-1))]}  #最大值
avg=$((sum/len))	#平均值

echo "avg    max    min"	#打印输出
echo "$avg    $max    $min"
echo "after sorted: ${num[@]}"
exit 0

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).