Compute the Average

Sort by

recency

|

356 Discussions

|

  • + 0 comments

    readarray -t V len=echo ${V[0]} sum=0 unset V[0] for a in ((a)) done result=echo "scale=3;len" | bc -l echo $result

  • + 0 comments
    read N
    result=0 
    for ((i=0; i < N; i++)); do
      read number
      result=$(echo "$result + $number" | bc)
    done
    avg=$(echo "$result / $N"  | bc -l)
    printf "%0.3f" "$avg"
    
  • + 0 comments

    This question is a bunch of floating point rounding error bullshit. You got it right close enough for all real-world applications if you got all but 1 on the submission.

  • + 0 comments

    Wrong Code uses integer arithmetic ($((sum + num))), which truncates floating-point numbers, leading to incorrect results when decimals are involved. For example, with inputs 1.5, 2.5, and 3.0, the sum becomes 6, resulting in an incorrect average of 2.000.

    Correct code uses bc for all arithmetic, which handles both integers and floating-point numbers correctly. With the same inputs, the sum becomes 7.0, and the correct average of 2.333 i

  • + 1 comment

    (easy solution is here : and if you are fail in one test and pass 5 test it is because you are not useing %0.3f .else use this bigner code. :)

    read n
    result=0
    for((i=0;i<$n;i++))
    do
        read num
        result=$(echo " $result + $num " |bc)
    done
    r=$(echo "$result / $n" | bc -l)
    printf "%0.3f" "$r"