Browse Source

first homework

XuZiang 5 months ago
commit
6615dea6c3
1 changed files with 67 additions and 0 deletions
  1. 67 0
      HomeWork_1.cpp

+ 67 - 0
HomeWork_1.cpp

@@ -0,0 +1,67 @@
+#include <iostream>
+#include <ctime>      // 随机数种子头文件 
+using namespace std;
+
+void generate_rand(int Size/*I*/, int num[]/*I*/)
+{
+	for (int i = 0; i < Size; i++)
+	{
+		num[i] = rand() % 100 + 1;
+	}
+
+	cout << "生成的随机数组:" << endl;
+	for (int i = 0; i < Size; i++)
+	{
+		cout << num[i] << " ";
+	}
+	cout << endl;
+}
+
+void sort_num(int Size/*I*/, int num[]/*I*/)
+{
+
+	for (int i = 0; i < Size - 1; i++)          // 对比总轮数
+	{
+		for (int j = 0; j < Size - i - 1; j++) // 每轮对比次数
+		{
+			if (num[j] > num[j + 1])
+			{
+				// 交换元素
+				int temp = num[j];
+				num[j] = num[j + 1];
+				num[j + 1] = temp;
+			}
+		}
+	}
+}
+
+void result(int Size/*I*/, int num[]/*I*/)
+{
+	cout << "排序后的数组:" << endl;
+	for (int i = 0; i < Size; i++)
+	{
+		cout << num[i] << " ";
+	}
+	cout << " " << endl;
+}
+
+int main()
+{
+	// 设置随机数种子
+	srand(time(NULL)); //防止每次生成随机数一样
+
+	const int Size = 10;
+	int num[Size];
+
+	// 1.生成随机数并查看
+	generate_rand(Size, num);
+
+	// 2.使用冒泡排序对随机数进行排序
+	sort_num(Size, num);
+
+	// 3.输出排序结果
+	result(Size, num);
+
+	system("pause");
+	return 0;
+}