gpt4 book ai didi

c - sort 函数不会打印排序后的数组?

转载 作者:行者123 更新时间:2023-11-30 16:26:12 27 4
gpt4 key购买 nike

我的排序函数不会打印排序后的数组?

我正在尝试编写一个程序来收集数组元素,对数组进行排序,然后打印每个元素的阶乘。如果数组未正确排序,我不想超前编写递归函数。我觉得这种类型很好;人们批评我使用 while 循环,但我还不知道另一种方法。任何意见都会受到赞赏。

#include <stdio.h>

int sorter(int numbList[]);
int getData(int numList[]);
//int recursive(int numList[]);

int main(void) {
int x;
int numberList[x];

getData(&numberList[x]);
sorter(&numberList[x]);

//recursive(&numberList[x]);
return 0;
}

//gets user input-data
int getData(int numbList[]) {
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d", &x);

printf("Enter the values for each element starting from first
element:\n");

for (i = 0; i < x; i++) {
scanf("%d", &numbList[i]);
}

printf("\nYou have filled the array list with\n");
for (i = 0; i < x; i++) {
printf("%d\n", numbList[i]);
}
return numbList[x];
}

//sorter function
int sorter(int numbList[]) {
int x;
int temp;
int swapped;

while (1) {
swapped = 0;
for (int i = 0; i < x; i++) {
if (i > numbList[i + 1]) {
temp = numbList[x];
numbList[x] = numbList[x + 1];
numbList[x + 1] = numbList[x];
swapped = 1;
}
if (swapped == 0) {
break;
}
}
printf("Array as sorted:\n");
for (int i = 0; i < x; i++) {
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}

//recursive factorial function
/* int recursive(int numbList[]) {
int b = 0;
numbList[b] *= numbList[b - 1];
return 0;
} */

最佳答案

代码中注释的一些提示:它仍然无法完成工作,但可以让你保持更好的状态......

int main(void) 
{
//uninitialized x!
int x;
//Even if you get a value for x, VLAs are depreciated
int numberList[x];
//Both calls get the adress of last value + 1 in numberList.
//So you a) go out of the array bounds, and b) why would you want
//the last element's address??
//Just use it like getData(numberList);
getData(&numberList[x]);
sorter(&numberList[x]);
return 0;
}

//gets user input-data
//What is the return value for?
int getData(int numbList[])
{
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d",&x);

printf("Enter the values for each element starting from first element:\n");
for(i=0;i<x;i++){
scanf("%d",&numbList[i]);
}

printf("\nYou have filled the array list with\n");
for(i=0;i<x;i++){
printf("%d\n",numbList[i]);
}
//see above
return numbList[x];
}

//sorter function
//Again, what and why return?
int sorter(int numbList[])
{
//uninitialized x!
int x;
int temp;
int swapped;

while(1)
{

swapped=0;
for(int i=0;i<x;i++)
{
//What do you compare here? Think.
if(i>numbList[i+1])
{
temp=numbList[x];
numbList[x]=numbList[x+1];
//What do you have temp for??
numbList[x+1]=numbList[x];
swapped=1;
}
//Pretty sure you want an else clause here
if(swapped==0)
{
break;
}
}

printf("Array as sorted:\n");
for(int i=0;i<x;i++)
{
printf("%d\t",numbList[x]);
}
return(numbList[x]);
}
}

关于c - sort 函数不会打印排序后的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138181/

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