Compute the Average

Sort by

recency

|

353 Discussions

|

  • + 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

  • + 0 comments

    (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"
    
  • + 0 comments
    #!/bin/bash
    
    read n
    str="0"
    
    # for i in {0..$n};
    for ((i=0; i<$n; ++i));
    do
        read a
        str="$str+$a"
    done
    echo "($str)/$n" | bc -l | xargs printf "%.3f"
    
  • + 0 comments
    read N
    
    sum=0
    
    for((i=1; i<=N; i++))
    do
        read X
        sum=$((sum+X))
    done
    
    expression="$sum / $N"
    
    result=$(printf %.3f $(echo $expression|bc -l))
    
    echo $result
    
  • + 1 comment
    read count_of_number
    if [[ "$count_of_number" -ge 1 && "$count_of_number" -le 500 ]]; then
        list_of_integers=0
        for number in $(seq 1 $count_of_number)
            do
                read numbers
                if [[ "$numbers" -ge -10000 && "$numbers" -le 10000 ]]; then
                list_of_integers=$(($numbers + $list_of_integers))
                else
                    echo "the number: $numbers is out of the range (-10000 <= x <= 10000)"
                    exit 1
                fi
            done
        average=$(echo "scale=4; $list_of_integers / $count_of_number" | bc -l | xargs printf "%.3f")
        echo $average
    else
        echo "the count of number is out of the range (1 <= N <= 500)"
    fi