问题及代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*ALL right reserved
*文件名;seventyeight.cpp
*作者;童宇
*完成日期2014年11月24日
*版本号v1.0
*问题描述:从文件中读取成绩并处理
*输入描述:
*程序输出:
*/
#include <fstream>
#include<cstdlib> //调用exit(1)需要包含cstdlib
#include <iostream>
#include <cmath>
using namespace std;
double ave;
void input_score(int s[], int n);
int get_max_score(int s[], int n);
int get_min_score(int s[], int n);
double get_avg_score(int s[], int n);
int count(int x, int s[], int n); //返回在数组s中n名同学中有多少人得x分(实参给出最高/低时,可以求最高/低成绩的人数)
int good (int s[], int n);
int bad (int s[], int n);
void output_index(int x, int s[], int n); //在函数中输出数组s中n名同学中得x分的学号(下标)
int main(void)
{
int score[5000]; //将score设为局部变量,通过数组名作函数参数,传递数组首地址,在函数中操作数组
int num,a,i=0;//小组人数也设为局部变量,将作为函数的实际参数
int max_score,min_score;
ifstream infile("myfristfile.dat",ios::in);
//测试是否成功打开,打开失败时(如要读的数据文件不存在)退出
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
//下面读取数据并完成处理,若数据需要多次使用,可以读入到数组中
while(infile>>a) //当到达文件尾,则循环处理结束。类似cin>>a,只不过数据来源于打开的文件
{
score[i]=a;
i++;
}
infile.close();
max_score=get_max_score(score, num);
cout<<endl<<"最高成绩为:"<<max_score<<",共有 "<<count(max_score, score, num )<<" 人。";
min_score=get_min_score(score, num);
cout<<endl<<"最低成绩为:"<<min_score<<",共有 "<<count(min_score,score, num )<<" 人。";
cout<<endl<<"平均成绩为:"<<get_avg_score(score, num);
ave=get_avg_score(score, num);
cout<<endl<<"获最高成绩的学生(学号)有:";
output_index(max_score,score, num);
cout<<endl<<"获最低成绩的学生(学号)有:";
output_index(min_score,score, num);
cout<<"\n获得优秀的有人数为:"<< good (score, num)<<"\n不及格的人数为:"<< bad (score, num);
cout<<endl;
return 0;
}
int get_max_score(int s[], int n)
{
int max=0,i;
for(i=0; i<n; i++)
{
if(max<s[i])
max=s[i];
}
return max;
}
int get_min_score(int s[], int n)
{
int min=100,i;
for(i=0; i<n; i++)
{
if(min>s[i])
min=s[i];
}
return min;
}
double get_avg_score(int s[], int n)
{
int i,sum=0,ave;
for(i=0; i<n; i++)
{
sum=sum+s[i];
}
ave=sum/n;
return ave;
}
int count(int x, int s[], int n)
{
int i,j=0;
for(i=0; i<n; i++)
{
if(s[i]==x)
j++;
}
return j;
}
void output_index(int x, int s[], int n)
{
int i;
for(i=0; i<n; i++)
{
if(x==s[i])
cout<<i<<" ";
}
}
int good (int s[], int n)
{
int i,j=0;
for(i=0; i<n; i++)
{
if(s[i]>=85)
j++;
}
return j;
}
int bad (int s[], int n)
{
int i,j=0;
for(i=0; i<n; i++)
{
if(s[i]<60)
j++;
}
return j;
}
运行结果: