C++实现学生成绩录入与查询系统(动态二维数组)

  1. 编写一个程序,能处理任意人数的学生成绩,人数由用户输入。

要求:1)人数n由用户输入;2)每行按照学号、成绩的顺序输入n行数据;3)按成绩降序排序,排序写成一个函数;4)设计一个循环过程,根据用户输入的名次序号,输出对应学生的学号和成绩,当用户输入-1时,程序结束。

例如:学生人数:2

          请按行输入所有学生的学号和成绩

          1401 85

       1402 66

       请输入需查找的名次:1

       1401 85

          请输入需要查找的名次:-1

       Over!

#include <iostream>
using namespace std;
void scoresSort(int **scores, int n);

int main()
{
	int n = 0;
	cout << "学生人数:" << endl;
	cin >> n;
	//创建动态二维数组
	int **scores = new int *[n];
	cout << "请按行输入所有学生的学号和成绩:" << endl;
	for (int i = 0; i < n; i++)
	{
		scores[i] = new int[2];
		cin >> scores[i][0] >> scores[i][1];
	}
	//排序
	scoresSort(scores, n);
	//查询
	int sortNum = 0;
	cout << "请输入需要查找的名次:";
	cin >> sortNum;
	bool search = true;
	while (search)
	{
		if (sortNum == -1)
		{
			search = false;
			cout << "Over!" << endl;
		}
		else
		{
			cout << scores[sortNum - 1][0] << " ";
			cout << scores[sortNum - 1][1] << endl;
			cout << "请输入需要查找的名次:";
			cin >> sortNum;
		}
	}
	delete []scores;
	return 0;
}
void scoresSort(int**scores, int n)
{
	int* temp = scores[0], key = 0;
	while (key < n - 1)
	{
		for (int i = n - 1; i > key; i--)
		{
			if (scores[i][1] > scores[i - 1][1])
			{
				temp = scores[i];
				scores[i] = scores[i - 1];
				scores[i - 1] = temp;
			}
		}
		key++;
	}
}

 


版权声明:本文为weixin_62804142原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。