LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   problem with awk command (https://www.linuxquestions.org/questions/linux-newbie-8/problem-with-awk-command-832707/)

newtolinux78 09-16-2010 09:19 PM

problem with awk command
 
I am new to linux and am trying to get help with a problem that I have been working on for awhile. I am supossed to use awk to find the average gpa. the file is set up so the the letter grade is in field 4 and the courses credits are in field 3. The command below is the last one that I came up with but it prints out the GPA is nan. I am just not sure what i am doing wrong.

awk 'BEGIN {gpa_total=0.0;course_total=$3;count=0}{if ($4=A){gpa=$3*4; gpa_total+=gpa;count++;}}{if ($4=B){gpa=$3*3; gpa_total+=gpa;count++}};{if($4=C){gpa=$3*2; gpa_total+=gpa;count++;}}{if ($4=D){gpa=$3*1; gpa_total+=gpa;count++;}}{if ($4=F){gpa=$3*0; gpa_total+=gpa;count++;}} END {print "GPA is" gpa_total/course_total}' grades.txt

evo2 09-16-2010 09:49 PM

Not really familiar with how to calculate a GPA but from your code it looks like you are trying to calculate a simple weighted mean, where you have assigned values of A->4, B->3, C->2, D->1. One problem I can see is that you are using "=" instead of "==" for the equivalence tests in the if statements. Anyway another approach would be to use an array.

Here is an untested example that may help point your in the right direction.

Code:

awk '
BEGIN {
  g=0.0;
  c=0.0;
  a["A"]=4;
  a["B"]=3;
  a["C"]=2;
  a["D"]=1;
}
{
  g+=a[$4]*$3;
  c+=$3;
}
END {
  print g/c;
}
'

Evo2.

newtolinux78 09-17-2010 07:39 AM

still confused
 
evo thank you for replying to me but i am still confused and can't figure this one out. I know that I need to keep a running total of $3 and $4 and I know that I need to take the count and divde each of these fields by it. I just can't figure out how to do it. I thought that the if/else if would work but it doesn't since i am getting the out put of GPA is nan. I changed the += to == but it doesn't work. if you have any other advice I would appriciate it.

evo2 09-17-2010 08:17 AM

The NAN is happening because the only place that you set course_total is in BEGIN{} where $3 is not defined. Therefore course_total will be set to zero. Then you divide by course_total (which is still zero) in END{} which gives you a NAN.

You also seem to have an unused variable "count" (although this should not cause any problems).

I also just noted that my sample code should have one more line in BEGIN{}
Code:

a["F"]=0;
Cheers,

Evo2.

PS. Try writing your code out over multiple lines and I think you'll see a few more bugs.


All times are GMT -5. The time now is 07:34 AM.