/*------------------------------------------------------ 【程序改错】 -------------------------------------------------------- 功能:用起泡法对10个整数从小到大排序。 ------------------------------------------------------*/ #include "stdio.h" /**********ERROR**********/ void sort(int x,int n) { int i,j,k,t; for(i=0;i<n-1;i++) /**********ERROR**********/ for(j=0;j<n-i;j++) /**********ERROR**********/ if(x[i]>x[i+1]) { t=x[j]; x[j]=x[j+1]; x[j+1]=t; } } main() { int i,n,a[100]; printf("please input the length of the array:\n"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); /**********ERROR**********/ sort(n,a); printf("output the sorted array:\n"); for(i=0;i<=n-1;i++) printf("%5d",a[i]); printf("\n"); }
时间: 2023-07-07 18:44:07 浏览: 67
本程序存在以下错误:
1. 函数声明和定义不匹配。函数声明 `void sort(int x,int n)` 中参数类型为 `int`,但是函数定义 `void sort(int x[], int n)` 中参数类型应该为 `int[]`。
2. 冒泡排序算法有误。内层循环的判断条件应该是 `j<n-i-1`,而不是 `j<n-i`。并且交换元素时应该使用 `x[j]` 和 `x[j+1]`,而不是 `x[i]` 和 `x[i+1]`。
修改后的程序如下所示:
```
#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("output the sorted array:\n");
for (i = 0; i < n; i++)
printf("%5d", a[i]);
printf("\n");
return 0;
}
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)