计算 states.txt 中列出的州的平均面积

计算 states.txt 中列出的州的平均面积

需要有人计算 中列出的各州的平均面积(以平方英里为单位)states.txt

States.txt(文件):

State           Population   SqMi      Region 
------------------------------------------
California           39.37   163.7       West
Texas                29.36   268.6      South
Florida              21.73    65.7      South
New_York             19.33    54.7  NorthEast
Pennsylvania         12.78    46.1  NorthEast
Illinois             12.59    57.9    Midwest
Ohio                 11.69    44.8    Midwest
Georgia              10.71    59.4      South
North_Carolina       10.60    53.8      South
Michigan             9.97    96.7    Midwest

输出应如下所示:

Average Area: 82.85 square miles

请注意,我的 awk 程序将像这样运行:

awk –f <file.awk> states.txt 

答案1

类似的东西可以完成这项工作:

BEGIN {sum=0} {sum+=$3} END {print "Average Area: "sum/(NR-2)" square miles"}

前两行可以忽略,因为求和运算会将字符串计数为零值

相关内容