问题
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