Calculating GPA in awk?

别来无恙 提交于 2019-12-25 02:12:05

问题


What I would like the code below to do is parse a file with lines similar to

CSC3320,SYSTEM LEVEL PROGRAMMING,3,1,A
CSC3210,ASSEMBLY LEVEL PROGRAMMING,3,1,B

and calculate the GPA based off of the equation sum of grade * credit hours / sum of credit hours. I attempt to do this by calculating the numerator and denominator separately and then dividing the two and printing the output.

calculate(){
  awk -F, '
    numerator=0;
    denominator=0;
    if($4==1) {
         if($5=="A"){
            numerator+=(4*$3);
            denominator+=$3
         } else if ($5 == "B"){
            numerator+=(3*$3);
            denominator+=$3
         } else if ($5 == "C"){
            numerator+=(2*$3);
            denominator+=$3
         } else {
         }
     }
  GPA = numerator/denominator
  printf "Your GPA is %d\n" GPA
  'my_course.txt

}

What I get is an error message saying

awk: line 4: syntax error at or near if
awk: line 18: syntax error at or near printf

my book doesn't elaborate much on if else if statements. So what exactly is wrong with how I have typed this out?


回答1:


This code works.

calculate(){
  awk -F, '
  BEGIN{printf "Your GPA is : "}
  numerator = 0.0;
  denominator = 0.0;
  /^CSC/{
    if($4=1) {
         if($5=="A"){
            numerator+=(4.0*$3);
            denominator+=$3;
         } else if ($5 == "B"){
            numerator+=(3.0*$3);
            denominator+=$3;
         } else if ($5 == "C"){
            numerator+=(2.0*$3);
            denominator+=$3;
         } else {
           ; 
        }
     }
   }
   END{printf"%f", (numerator/denominator)}
  ' my_course.txt
}


来源:https://stackoverflow.com/questions/15688488/calculating-gpa-in-awk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!