C++期末练习题2
要求
有六位学生,学号从1
到6
,语文、数学两门课的成绩分别存放在一维数组chinese
、math
中。
要求:
- 编写排序函数
sort
,在主函数中调用此函数按成绩高低排名; - 编写求平均分的函数
average
,在主函数中调用此函数求课程的平均分; 编写函数
lessAverage
,在主函数中调用此函数求低于平均分的人数。(注:同一科目,学生成绩不相同)
输出结果
题目
#include <iostream>
using namespace std;
/**********Program**********/
/********** End **********/
int main() {
double chinese[6], math[6]; //语文成绩数组、数学成绩数组
int i;
int stuId[6] = {1,2,3,4,5,6}; //学号数组
//输入对应的成绩
for (i = 0; i < 6; i++) {
cout << "请输入成绩(语文、数学):";
cin >> chinese[i] >> math[i];
}
//以语文成绩为关键字,对语文成绩数组&学号数组排序
sort(chinese, stuId, 6);
cout << "语文课名次如下:" << endl;
cout << "名次" << '\t' << "学号" << '\t' << "语文成绩" << endl;
for (i = 0; i < 6; i++) {
cout << i + 1 << '\t';
cout << stuId[i] << '\t' << chinese[i] << endl;
}
//重置学号数组
for (i = 0; i < 6; i++) stuId[i] = i + 1;
//以数学成绩为关键字,对数学成绩数组&学号数组排序
sort(math, stuId, 6);
cout << "数学课名次如下:" << endl;
cout << "名次" << '\t' << "学号" << '\t' << "数学成绩" << endl;
for (i = 0; i < 6; i++) {
cout << i + 1 << '\t';
cout << stuId[i] << '\t' << math[i] << endl;
}
//调用average函数计算各科平均分,调用lessAverage统计各科低于平均分的人数
cout << "语文课平均成绩为:" << average(chinese, 6) << endl;
cout << "语文课低于平均分的人数为" << lessAverage(chinese, 6) << "人" << endl;
cout << "数学课平均成绩为" << average(math, 6) << endl;
cout << "数学课低于平均分的人数为" << lessAverage(math, 6) << "人" << endl;
return 0;
}
参考答案
void sort(double * score, int * id, int n) //或void sort(double score,int id,int n)
{
int i, j, max, tempId;
double temp;
for (i = 0; i < n - 1; i++)
// 倒数最后第二次个元素固定,最后一个元素也固定了,故只需要n - 1次循环
// 每次找到待排序区的最大值与待排序区第一个元素交换,每次循环第i个学生拍好序
{
max = i;
for (j = i + 1; j < n; j++)
if (score[j] > score[max]) // 在i+1 --- n - 1中找到最大值
max = j;
// 交换score[i]与score[max]
temp = score[i];
score[i] = score[max];
score[max] = temp;
// 交换id[i]与id[max]
tempId = id[i];
id[i] = id[max];
id[max] = tempId;
}
}
double average(double * score, int n) //或 double average(double score,int n)
{
double avg = 0;
int i;
for (i = 0; i < n; i++)
avg += score[i]; //计算总成绩
avg /= n; //计算平均值
return avg;
}
int lessAverage(double * score, int n) // 或 int lessAverage(double score,int n)
{
int i, count = 0;
for (i = 0; i < n; i++)
if (score[i] < average(score, n)) //小于平均值,count++
count++;
return count;
评论区(暂无评论)