[ create a new paste ] login | about

Link: http://codepad.org/IiHq4W2t    [ raw code | output | fork ]

C++, pasted on Mar 13:
/*
輸入同學成績,將成績用低到高排序(函數),還有要輸出幾個人的成績也要設定

(我自己想要加上人名的部份)
*/

#include <iostream>	
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;

void output(int* score, int people)	//score陣列存了每個人的分數,people代表當初設定要輸入幾個人的成績
{
	if(people == 1)	//如果只有一個人,那就直接印出來就好
		cout << *score << endl;
	else
	{
		for(int i = 1; i < people; i++)	//這個for巢狀迴圈是做排序用
		{
			for(int j = 0; j < i; j++)
			{
				if(*(score + j) > *(score + i))	//我設定分數由低到高排列,如果score[j]比score[i]還大的話,就把兩個調換位置,沒有的話就沒事
				{
					int swap = *(score + i);
					*(score + i) = *(score + j);
					*(score + j) = swap;
					/*
					我希望存著每個人名字的每個string也是在這裡重新排序
					*/
				}
			}
		}

		for(int k = 0; k < people; k++)	//把score陣列裡已經排序好的資料都印出來
			cout << *(score + k) << " ";

		cout << endl;
	}
}

int main()
{
	int n = 0;
	cout << "Please enter the number of the student: ";	//先輸入要輸入幾個人的成績
	cin >> n;
	cout << endl;

	int *score = new int[n];
	//這裡希望也能動態建立n個空string
	
	for(int i = 0; i < n; i++)	//看當初輸入幾個人,就能輸入幾次成績
	{
		/*
		我希望在輸入成績之前,能先輸入這個學生的名字
		*/
		int grade = 0;
		cout << "Please enter the no." << i+1 << "student's grade: ";
		cin >> grade;
		cout << endl;
		*(score + i) = grade;
	}

	output(score, n);	//扔到output()函式裡進行排序及印出來

	return 0;
}


Output:
1
2
Please enter the number of the student: 



Create a new paste based on this one


Comments: