bash总和平均......等等

时间:2016-11-03 16:35:11

标签: bash loops variables if-statement

我试图搞定这个

Enter Incidents
Mon 14 
Tue 5
Wed 12

Incidents

Mon 14
Tue 5
Wed 12

Total 38

Average 7.6
------------------------

Mon incidents is the highest 11
Tue incidents is the lowest 2
------------------------

Enter a Day that you'd like to see how many incidents occurred? Wed 
12 Incidents
------------------------

到目前为止,我做了总和平均值,Max和min。

问题是如何输出" 周一是最高的11.我能够找到最小值和最大值但是不能打印当天匹配的最大值和最小值......

#!/bin/bash

echo " ----Enter Incidents-----"



echo -n "Mon= " 
read days[0]


echo -n "Tue= "
read days[1]


echo -n "Wed= " 
read days[2]






echo " ------Incidents--------"


total=`expr ${days[0]} + ${days[1]} + ${days[2]}`


echo "Toatal is= " $total 


ave=`expr $total \/ 3`


echo "Average= " $ave



max=${days[0]} 

min=${days[0]} 



for i in "${days[@]}"

do

if [[ "$i" -gt "$max" ]]; then 

    max="$i" 
fi 


if [[ "$i" -lt "$min" ]]; then

    min="$i" 

fi 

done 


echo "Max is:" $max

echo "Min is:" $min 


this is killing me lol 
Mon incidents is the highest 11
Tue incidents is the lowest 2
------------------------

Enter a Day that you'd like to see how many incidents occurred? Wed 
12 Incidents
-------------------------------

2 个答案:

答案 0 :(得分:0)

替换

read -p "Mon= " days[0]

通过

expr something

也替换

$(( somthing )) # space matters

通过

cb_B_8

请格式化代码,以便在问题中可读。

答案 1 :(得分:0)

假设你的日子和写作一样(你使用索引但你可以使用'星期二''星期三等等):

for i in ${!days[@]}; do
    if [[ ${days[$i]} -gt "$max" ]]; then 
        maxday="$i" 
    fi 
    if [[ ${days[$i]} -lt "$min" ]]; then
        minday="$i" 
    fi 
done

现在你可以打印minday和天[$ minday]。如果将键保留为索引,则需要切换以将索引转换为日期。如果你想让你的数组格式化:

declare -A days    
echo Tue=
read days['Tue']

等。如果您定义了几天,并使用上面的循环,则可以将结果打印为:

echo $maxday yields the maximum ${days[$maxday]}