酷代码 AI
菜单
服务商

修复 C++ 代码错误:实现随机数组生成与插入排序

It looks like you're trying to write a C++ program that generates an array of random integers, displays the original array, sorts the array using insertion sort, and then displays the sorted array. However, there are several syntax and logical errors in your code. Let's correct them and complete the `insertsort` function. Here is the corrected and completed version of your program: ```cpp #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int n = 10; const int min = 10; const int max = 99; // Function to generate a random number between min and max int getrand(int min, int max) { return (rand() % (max - min + 1) + min); } // Function to fill the array with random numbers void set(int r[], int n) { for (int i = 0; i < n; i++) { r[i] = getrand(min, max); } } // Function to display the array void show(int r[], int n) { for (int i = 0; i < n; i++) { cout << r[i] << " "; } cout << endl; } // Function to perform insertion sort void insertsort(int r[], int n) { for (int i = 1; i < n; i++) { int key = r[i]; int j = i - 1; while (j >= 0 && r[j] > key) { r[j + 1] = r[j]; j--; } r[j + 1] = key; } } int main() { srand(time(0)); // Seed the random number generator int a[n]; set(a, n); // Fill the array with random numbers cout << "原序列: "; show(a, n); // Display the original array insertsort(a, n); // Sort the array cout << "新序列: "; show(a, n); // Display the sorted array return 0; } ``` Explanation of Changes: 1. Function Prototypes and Definitions: - `getrand(int min, int max)`: Generates a random number between `min` and `max`. - `set(int r[], int n)`: Fills the array `r` with `n` random numbers. - `show(int r[], int n)`: Displays the array `r`. - `insertsort(int r[], int n)`: Sorts the array `r` using the insertion sort algorithm. 2. Syntax Fixes: - Corrected the function definitions and calls. - Added missing semicolons and braces. - Fixed the `insertsort` function to properly implement the insertion sort algorithm. 3. Main Function: - Seeded the random number generator with `srand(time(0))`. - Called `set` to fill the array with random numbers. - Displayed the original array using `show`. - Sorted the array using `insertsort`. - Displayed the sorted array using `show`. This should work as expected, generating a random array, displaying it, sorting it, and then displaying the sorted array. ######[AI写代码神器 | 690点数解答 | 2024-10-31 10:11:20]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]