We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

- Practice
- Linux Shell
- Bash
- Compute the Average
- Discussions

# Compute the Average

# Compute the Average

pranitbose_15 + 0 comments *Short and crisp*read n arr=($(cat)) arr=${arr[*]} printf "%.3f" $(echo $((${arr// /+}))/$n | bc -l)

Odiumediae + 0 comments Well, this was certainly the most annoying Bash challenge I've encountered thus far. My code is probably not perfect at all, but I hope it will spare a few people the trouble of getting past this buggy challenge:

sum=0 read n while read -r line || [[ -n "$line" ]]; do sum=$(($sum + $line)) done printf "%.3f" $(echo "scale=10; $sum/$n" | bc -l)

baadf00d + 0 comments Two Liner

read n printf "%.3f" $(echo "("$(cat)")/$n" | tr ' ' '+' | bc -l)

ariessa + 0 comments **Beware of spacing**. For example:read n for i in $(seq 1 $n); do read num sum=$((sum + num)) done printf "%.3f" $(echo "$sum/$n" | bc -l)

read n for i in $(seq 1 $n); do read num sum = $((sum + num)) done printf "%.3f" $(echo "$sum/$n" | bc -l)

The codes above produce different outputs. The first one is correct. p/s: Don't make the same mistake like me.

davcdhanesh1 + 0 comments for test #2, my script is giving answer as 4696.946, but according to test it should be 4696.947. Is that a valid failure ? I am using "sum / $total_numbers" | bc -l)" command to calculate final average value.

Load more conversations

Sort 224 Discussions, By:

Please Login in order to post a comment