我必须编写一个脚本,以一些数字作为输入。我需要获取最大数字以及最大数字的频率。我该怎么做呢?我必须使用 for 循环吗?
这就是我所拥有的:
while read -p "Enter a value:" NUMBER ; do
if [[ $NUMBER -eq 0 ]] : then
break
else
if [[ $NUMBER -gt $max_Value ]] ; then
max_Value=$NUMBER
fi
fi
done
答案1
此实现不使用结构。我更正了拼写错误并使用了您的编码风格:
max_Freq=0 # initialization of frequency (because of increment below can work)
while read -p "Enter a value:" NUMBER ; do
if [[ $NUMBER -eq 0 ]] ; then
break; # exit while with entering 0
else
if [[ $NUMBER -eq $max_Value ]] ; then
max_Freq=$((max_Freq+1)) # increment frequency of max
fi
if [[ $NUMBER -gt $max_Value ]] ; then # we have new max number entered
max_Value=$NUMBER # remember this number
max_Freq=1 # initialization of frequency of this number
fi
fi
done
# on exit while loop print out statistics
echo "Max value $max_Value was entered $max_Freq times";
# Usage example:
# $ bash m.sh
# Enter a value:4
# Enter a value:4
# Enter a value:5
# Enter a value:0
# Max value 5 was entered 1 times