gpt4 book ai didi

C 程序在 scanf 语句后没有响应

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:46 25 4
gpt4 key购买 nike

我的代码编译并运行。但是在接受输入后它不执行程序的下一条语句。

它接受数组的所有输入元素,然后什么都不做。我认为在 for 循环内的第二个 scanf 语句之后有问题。

我不确定代码是否正确,但在编译和运行之后,我期望它应该给出最终输出,即使它不符合预期(或不正确)。

我正在使用 Code::Blocks(16.01) 作为 IDE。我的操作系统是 Windows 8.1(64 位)。

我的代码:

#include <stdio.h>

void quick(int *, int, int);

int main() {
int n, i, pivot, j, k, l, u;

printf("Give size\n");
scanf("%d", &n);

int a[n];
printf("Enter the list\n");
for (i = 1; i <= n; i++)
scanf("%d", &a[i]);

quick(a, 1, n - 1);
printf("\nSorted numbers are\n");
for (i = 1; i <=n; i++)
printf("%d ", a[i]);
printf("\n");

return 0;
}

void quick(int a[], int l, int u) {
int pivot, j, temp, i;
pivot = a[l];
i = l;
j = u;

while (i <= j) {
if (a[i] > pivot && a[j] < pivot) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else if (a[i] < pivot)
i++;
else if (a[j] > pivot)
j--;
}
quick(a, l, j - 1);
quick(a, j + 1, u);
}

Output of the program

最佳答案

正如其他人在评论中指出的那样,您犯了一些错误:

  1. 您已将数组声明为 int a[n] ;并且数组索引从 0 开始,那么为什么要传递数组就像它的索引从 1 开始一样?您需要将这些 for 循环更改为:for(i=0;i<n;i++)然后你像这样调用快速排序:quick(a,0,n-1); .
  2. 您的快速排序逻辑似乎有缺陷。您选择a[l]作为你的支点,但你将其包含在你的分区逻辑中。您也没有检查递归的基本条件,即 l < u .
  3. 对数组进行分区后,您应该将枢轴与分区的中间元素交换(即上半部分的最后一个元素或下半部分的第一个元素,具体取决于您的选择)。我改变了你的快速排序功能,比如 this .我能够看到所需的输出。

希望对您有所帮助。

关于C 程序在 scanf 语句后没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45115324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com