我的作业是:编写一个函数,获取一个整数数组。 N * 2 = 数组的大小
,因为 N = 您将扫描多少对情侣
。该数组包括一对数字。我需要打印复数索引上的数字按升序排列的数字。
示例:
Input: 4, -6, 2, 10, 3, 0, 1, 9
Ouput: 1, 9, 2, 10, 3, 0, 4, -6
With N = 4.
如果我设置N = 4
,它只允许我扫描 4 个数字,而不是 8 个。这是为什么呢?它甚至在第 4 个扫描数字后打印出奇怪的数字。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, sz1, sz2;
int i, j, cs, cs2;
printf("Enter the value of n:\n");
scanf("%d", &n);
int array[2*n];
printf("Enter the numbers in the array:\n");
for(i=0; i<2*n; i++)
{
scanf("%d", &array[i]);
i++;
}
for(i=0; i<2*n; i++)
{
for(j=i+1; j<2*n; j++)
{
if(array[i]>array[j] && i%2==0 )
{
cs=array[i];
array[i]=array[j];
array[j]=cs;
cs2=array[i+1];
array[i+1]=array[j+1];
array[j+1]=cs2;
}
}
}
for(i=0; i<n*2; i++)
printf("%d %d\n", array[i], array[i]);
return 0;
}
最佳答案
在第一个循环结束时,您不应该执行 i++
,因为您已经在 for
子句中执行了。按照您的方式进行操作,在每个循环中,i
都会递增两次,从而使您完成一半的循环。
此外,当您尝试从数组中读取所有其他元素时,未设置,因此它可能包含垃圾数据。
关于C - 如何将一对夫妇的第一个数字按升序排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44114652/