gawk - 尝试致命除以零

gawk - 尝试致命除以零

所以我写了一个简单的 gawk 脚本,名为 script.awk,如下所示

  
#! /usr/bin/gawk -f

# Sorts by ascending order
# ROCINFO["sorted_in"] = "@ind_num_asc"
BEGIN{
    FS=","
    drunkCases=0
    totalCases=0
    friSatAccident=0
    totalCasesMI=0
    drunkCasesMI=0
    darkCasesMI=0
}
#Count total cases so we can calculate proportions
NR>1{totalCases+=1}

#Count drunk driving cases
NR>1 && $52>=1{drunkCases+=1}

#Count accidents on Friday or Saturday
NR>1 && ($15 == 6 || $15 == 7) {friSatAccident+=1}

#Count total Accident cases in michigan
NR>1 && $1 == 26 {totalMI+=1}

#Count total Drunk drivers in michigan accidents
NR>1 && $1 == 26 && $52 >= 1 {drunkCasesMI+=1} 

# Counts accidents in michigan that occured in the dark
NR>1 && $1 == 26 && ($36 == 2 || $36 == 3 || $36 == 6) {darkCasesMI+=1}

#array that holds number of people for each state code in a key where the key is the state code. 
NR>1{stateAccCount[$1]+=$9}
END{
    print "DD Proportion: " drunkCases/totalCases
    print "Friday/Saturday Proportion: " friSatAccident/totalCases
    print "MI DD Proportion: " drunkCasesMI/totalCasesMI
    print "MI Dark Proportion: " darkCasesMI/totalCasesMI
    print "State Code,# People"
    for (key in stateAccCount){
        print key","stateAccCount[key]
    }
}

但是,当我尝试运行它时,出现错误:

Your code produced an error when running
gawk: script_cnv.awk:37: (FILENAME=- FNR=10) fatal: division by zero attempted

Stdout is
DD Proportion: 0.666667
Friday/Saturday Proportion: 0.444444

我不明白我做错了什么。我尝试再次通读我的脚本,以确保没有拼写错误,也没有发现任何内容。我很困惑为什么它试图除以零,这些值不应该为零。我究竟做错了什么

答案1

有一个变量从未分配过零以外的值,并且在进行END除法时,该变量是除数,这就是致命错误“尝试除以零”的原因。

> grep -n totalCasesMI script.awk
10:    totalCasesMI=0
37:    print "MI DD Proportion: " drunkCasesMI/totalCasesMI
38:    print "MI Dark Proportion: " darkCasesMI/totalCasesMI

请注意,如果缺少第 10 行,也会发生同样的情况,因为awk变量将被评估为空字符串,如果尚未初始化,则评估为零。

对于这种情况,一个很好的解决方法是首先测试除数是否为零,即使您修改了代码以实际为该变量赋值之后,该解决方法也很有用。条件语句会很好,如下所示:

(totalCasesMI==0 ? "N/A" : drunkCasesMI/totalCasesMI)

相关内容