Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4.5) Please use the solution to HW 7, problem 2, as a template to write a shell/

ID: 3805053 • Letter: 4

Question

4.5) Please use the solution to HW 7, problem 2, as a template to write a shell/awk script, myaverage4, that reads in 4 numbers and then uses a self-defined function to compute the average. The average should be displayed in the main program, not inside the function. Please use the following testing cases to test your script:

$ ./myaverage4 2 7 4 3

The average is 4

$./myaverage4 -2 -1 -4 -5

The average is -3

This is what i have:

#!/usr/bin/

echo $1 $2 $3 $4| awk '

{

print avg($1 $2 $3 $4)

}

function avg (a,b,c,d){

x=0

y=0

            x = a + b + c + d

            y = x / 4

            return y

}'

it doesnt seem to be working.

Explanation / Answer

The code you wrote is good actually. There is only one thing that you have missed and so the result printed is not proper.

The change you need to do in your script is: when you are printing a value of average using $1 to $4 variables, write it like print avg($1, $2, $3, $4) instead of print avg($1 $2 $3 $4).

When you write the variables without separating them with the commas, they are treated as they are written continuously. Suppose you wrote like ./myaverage 1 2 3 4 then the print avg(1 2 3 4) it becomes as per your code and when this is passed in the function to store in a,b,c and d, the values are : a=1234, b, c and d unknown so in finding average the 1234/4 is done instead of (1+2+3+4)/4. To solve this, just insert the commas in this line and the script is running perfectly because now it knows every value is separate so a=1, b=2, ... is done which is desired. So it will give you the correct result.

Please comment if there is any query. Thank you. :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote