Bird
0
0

How can you calculate the average of three integer variables x, y, and z using arithmetic expansion in bash?

hard🚀 Application Q9 of 15
Bash Scripting - Quoting and Expansion
How can you calculate the average of three integer variables x, y, and z using arithmetic expansion in bash?
Aavg=$((x + y + z / 3))
Bavg=$(((x + y + z) / 3))
Cavg=$((x + y + z) / 3.0)
Davg=$((x + y + z) // 3)
Step-by-Step Solution
Solution:
  1. Step 1: Understand integer division in bash

    Bash arithmetic expansion supports integer math only.
  2. Step 2: Evaluate each option

    avg=$(((x + y + z) / 3)) correctly sums all variables then divides by 3. avg=$((x + y + z / 3)) divides z by 3 first due to operator precedence. avg=$((x + y + z) / 3.0) uses floating point which is unsupported. avg=$((x + y + z) // 3) uses // which is invalid in bash.
  3. Final Answer:

    avg=$(((x + y + z) / 3)) -> Option B
  4. Quick Check:

    Correct average calculation = avg=$(((x + y + z) / 3)) [OK]
Quick Trick: Use parentheses to control order in $(( )) [OK]
Common Mistakes:
MISTAKES
  • Ignoring operator precedence
  • Using floating point in $(( ))
  • Using invalid operators like //

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes