gpt4 book ai didi

c - 为什么排序后数组元素发生了变化,C

转载 作者:行者123 更新时间:2023-11-30 20:50:12 34 4
gpt4 key购买 nike

数组的元素发生了变化,变成了一些永远不会被输入的数字。

#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 1000

int cmp(int a, int b)
{
return a>b;
}

void sort(int *data, int n, int (*cmp)(int, int))
{
for (;n>1;n--)
{
int i_max = 0;
for(int i = 1;i<n;i++)
if(cmp(data[i],data[i_max])) i_max = i;

int temp = data[i_max];
data[i_max] = data[n-1];
data[n-1] = temp;
}
}


int main()
{
int data[MAX_SIZE] , n;
scanf("%d",&n);
for(int i = 0 ; i < n ; i++)
{
int m;
puts("*****************");
scanf("%d",&m);
for(int j = 0 ; j < m ; j++)
scanf("%d",data+j);
sort(data, m, cmp);
puts("after sorting:");
for(int j = 0 ; j < m ; j++)
{
printf("%d ",data[j]);
}
puts("\n*****************");
}

return 0;
}

输入:

5
5
12
346
5676434535
765654543596
3543456
6
5783945
5293
237894
273894
73
237482
4
27895
719287349723947
1
34
7
3472893
74897598347
757
178
579875498234
129
84
5
420938
23
837485
279
29871

输出:

*****************
after sorting:
12 346 3543456 1150364908 1381467239
(the last two numbers were never input before, and the former number disappeared)
*****************
*****************
after sorting:
73 5293 237482 237894 273894 5783945
*****************
*****************
after sorting:
1 34 27895 586728235
*****************
*****************
after sorting:
84 129 178 757 3472893 54913274 1883154315
*****************

最佳答案

您提供的输入不适合 int。例如,765654543596(十六进制 B244912CEC)超过 32 位,这可能是您的 int 宽度。如果将其截断为 32 位,您将准确地看到输出中看到的神秘 1150364908(十六进制 44912CEC)。

关于c - 为什么排序后数组元素发生了变化,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49322808/

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