C语言技能考试题-起泡排序程序改错
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
The given C language program is supposed to sort 10 integers in ascending order using the bubble sort method. However, there are errors in the code that need to be corrected. The correct code should be as follows: ```c #include <stdio.h> void sort(int x[], int n) { int i, j, t; for(i = 0; i < n - 1; i++) { for(j = 0; j < n - i - 1; j++) { if(x[j] > x[j + 1]) { t = x[j]; x[j] = x[j + 1]; x[j + 1] = t; } } } } int main() { int i, n, a[100]; printf("Please input the length of the array:\n"); scanf("%d", &n); printf("Please input %d integers:\n", n); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } sort(a, n); printf("The sorted array is:\n"); for(i = 0; i < n; i++) { printf("%d ", a[i]); } return 0; } ``` In the corrected code: 1. The `sort` function now takes an array `x[]` and an integer `n` as parameters. 2. The loops in the `sort` function now correctly iterate over the array indexes. 3. The comparison in the `if` statement inside the `sort` function compares elements at indexes `j` and `j + 1`. 4. The `main` function now correctly reads input integers into the array, calls the `sort` function, and then prints the sorted array. This corrected code ensures that the program sorts 10 integers using the bubble sort method from smallest to largest.
剩余49页未读,继续阅读