在awk中计算GPA? [英] Calculating GPA in awk?

查看:70
本文介绍了在awk中计算GPA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要下面的代码执行的操作是使用类似于

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

,并根据等值的等级总和*学分/学分/总学分计算出GPA.我尝试通过分别计算分子和分母,然后除以两者并打印输出来实现.

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:第4行:if或附近的语法错误
awk:第18行:printf或附近的语法错误

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

我的书没有详细说明if语句.那么我输入的内容到底出了什么问题?

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

推荐答案

此代码有效.

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
}

这篇关于在awk中计算GPA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆