Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中气泡排序数组错误:第二个整数始终为零_C_Arrays_Sorting_Bubble Sort - Fatal编程技术网

C中气泡排序数组错误:第二个整数始终为零

C中气泡排序数组错误:第二个整数始终为零,c,arrays,sorting,bubble-sort,C,Arrays,Sorting,Bubble Sort,我编写了一个程序,对长度不超过20个整数的数组进行冒泡排序,其内容由用户决定。我遇到的问题是,打印排序数组时,数组中的第二个整数始终为0,从而导致无法打印排序数组中的最大整数。下面是我的代码: #include <stdio.h> int main() { int array[20]; int n; int c; int d; float swap; printf("Please enter how many numbers you want to sort

我编写了一个程序,对长度不超过20个整数的数组进行冒泡排序,其内容由用户决定。我遇到的问题是,打印排序数组时,数组中的第二个整数始终为0,从而导致无法打印排序数组中的最大整数。下面是我的代码:

#include <stdio.h>

int main()
{
  int array[20];
  int n;
  int c;
  int d;
  float swap;
  printf("Please enter how many numbers you want to sort (up to 20):\n\t");
  scanf("%d", &n);
  if (n >= 2)
  {
    for (c = 0; c < n; c++)
    {
      printf("Please enter the next number:\n\t");
      scanf("%d", &array[c]);
    }
    for (c = 0; c < (n - 1); c++)
    {
      for (d = 0; d < (n - c); d++)
      {
        if (array[d] > array[d + 1])
        {
          swap = array[d];
          array[d] = array[d + 1];
          array[d + 1] = swap;
        }
      }
    }
    for (c = 0; c < n; c++)
    {
      printf("%d\n", array[c]);
    }
    printf("Here are the results in ascending order:\n");
  }
  else
  {
    printf("Since you have fewer than two numbers, they are already sorted!\n");
  }
  return 0;
}
#包括
int main()
{
int数组[20];
int n;
INTC;
int d;
浮动互换;
printf(“请输入要排序的数字数量(最多20个):\n\t”);
scanf(“%d”和“&n”);
如果(n>=2)
{
对于(c=0;c数组[d+1])
{
交换=数组[d];
数组[d]=数组[d+1];
数组[d+1]=交换;
}
}
}
对于(c=0;c
您应该使用的是:

for (d = 0; d < n - c - 1; d++)
以及:


(a) 有可能,但决不能保证。由于
array
是一个局部变量,未初始化元素的值将是任意的

如果您的代码有时能正常工作,这是因为-您可以通过确保数组元素全部初始化为零来获得可重复的故障:

int array[20] = {0};
然后,因为它是可复制的,所以您可以进行此答案中给出的更改来修复它



(b) 另一方面,在本例中,
0
没有一直冒泡到底的原因是因为它在第一次传递期间被新引入到数据中。这意味着对数据进行完全排序所需的传递次数少了一次。

这是一个巨大的代码混乱。尝试将您的排序代码推入一个适当的函数中,以将其模块化并克服这一混乱。为什么
swap
a
float
?这并不是说这有什么区别,而是很奇怪。此外,请正确缩进代码;这将使它更容易理解和调试。让我说一个不正确的缩进比没有缩进更糟糕。在将
swap
更改为
int
(因此它为我编译)之后,它似乎也能工作。任何一个特定的测试用例都不应该这样做吗?谢谢你@paxdiablo的帮助
for (d = 0; d < n - c - 1; d++)
1 0 1 3 4 5
1 1 3 4 5 9
int array[20] = {0};