你好,我用 bash 脚本制作了这个程序,我需要计算平均值,我试了很多次,但它不起作用
#!/bin/bash
declare -A grades
for (( c=1 ; c<=5 ; c++))
{
read -p "enter name,course grade of 5: " course grade
grades[$course]=$grade
}
echo "your grades is"
echo ${grades[@]}
echo
echo "this is all your courses name and grades"
for c in ${!grades[*]}
{
echo " $c : ${grades[$c]}"
}
unset mygrades
答案 0 :(得分:0)
您将需要在循环浏览成绩时创建总成绩,并使用 bc 之类的东西来获得带有小数位的平均值。因此,请使用您的原始代码:
#!/bin/bash
declare -A grades
for (( c=1 ; c<=5 ; c++))
{
read -p "enter name,course grade of 5: " course grade
grades[$course]=$grade
}
echo "your grades is"
echo ${grades[@]}
echo
echo "this is all your courses name and grades"
for c in ${!grades[*]}
{
echo " $c : ${grades[$c]}"
(( cnt++ )) # Counting elements in the array
if [[ "$cnt" -ge "(( ${#grades}-5 ))" ]]
then
(( total+=${grades[$c]} )) # Get a running total of the grades in index of array is one of the last 5
fi
}
unset mygrades
av=$(echo "scale=2;$total/5" | bc) # Calculate the average using bc, setting the decimal places to 2 by using scale and reading the result into av
echo "Your average grade is $av"