在前面的文章《用switch语句制作菜单》中,我们定义了四个函数分别求平均成绩、找最高成绩、统计不及格人数和统计80分以上人数。在四个函数中,都有打开文件、读文件、关闭文件的操作。当操作次数多,文件中数据量大时,这是一种非常低效率的做法,因为磁盘操作是一种耗时的过程。因此,我们有必要更新程序,找到新的方法来减少文件操作的次数。
在原来程序的每个函数中,只是定义了一个变量score来存储成绩,每读一个成绩,就处理一个,后面读进来的成绩会覆盖前面的成绩。也就是说每个函数都没有保存成绩,因此每个函数中都必须重新读文件。现在学完数组了,我们可以考虑用数组来保存成绩,具体过程是:在主函数中定义一个数组score,然后打开文件,将文件中的数据全部读入到score数组中,最后将score数组以参数的形式传递给四个处理成绩的函数。这样,四个函数就共享score数组进行数据处理,没有必要再分别读文件。给四个函数增加数组形参,并对代码进行相应的修改即可。具体代码如下: