【发布时间】:2015-03-31 18:07:08
【问题描述】:
我正在尝试编辑我一年前制作的程序,但我似乎在某个地方失败了,因为我无法获得我想要的结果。我想让程序从低到高对数字进行排序,用户应该输入数字,直到按下 0。很想从高级的人那里得到一些帮助!
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* List;
void Add(struct node* p, int d)
{
struct node* q;
q = malloc(sizeof(struct node));
if (q == NULL)
printf("Not enaugh memory!");
else{
q->data = d;
if (List == NULL || List->data < d)
{
q->next = List;
List = q;
} else {
struct node *ptr = List;
while ((ptr->next != NULL) && (ptr->next->data>d)){
ptr = ptr->next;
}
q->next = ptr->next;
ptr->next = q;
}
}
}
int main()
{
int n, i, a;
printf("How many numbers are you going to enter? ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\nEnter a number: ");
scanf("%d", &a);
Add(List, a);
}
printf("\nEntered and sorted numbers are: ");
struct node *ptr = List;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n\n");
system("PAUSE");
return 0;
}
【问题讨论】:
-
请缩进您的代码。
-
请尽可能详细地解释你认为这个程序应该做什么,它做了什么,以及为什么这种行为让你感到困惑.
-
until 0 is pressed..魔法在哪里? -
另外,never use
scanffor anything。仅查看您的代码,我发现至少有两个地方可能在做一些对您没有意义的事情,因为scanf很糟糕。如果你改用fgets和strtol,这些问题就会消失。 -
1.现在它会询问您要输入多少个数字。相反,它应该让您输入数字,直到输入“0”。 2.现在数字是按从高到低的顺序排列的,应该是另一种方式 - 从低到高的顺序。
标签: c