【发布时间】:2012-03-25 22:20:56
【问题描述】:
我的任务是让用户以“99 年 1 月 12 日”的形式输入包含月、日和年的 n 行。
我必须先使用 qsort 按年,然后按天,然后按月,按时间顺序对日期列表进行排序。
我的问题是我不确定如何对多个索引进行 qsort。我已经完成了它工作正常的一年,但在那之后我不知道如何在当天进行 qsort ,因为它肯定会按天排序,但是这些年又会变得混乱?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int (*compfn)(const void*, const void*);
struct date
{
char month[9]; //Maximum of 9 characters in a month
int day; //The day of the month (e.g. 18)
int year; //The year of the date
};
int sortDates(struct date *elem1, struct date *elem2)
{
if (elem1 -> year < elem2 -> year)
{
return -1;
}
else
if (elem1->year > elem2->year)
{
return 1;
}
else
return 0;
}
main()
{
int n;
int i;
scanf("%d", &n);
struct date *list;
list = (struct date *)malloc((n * sizeof(struct date)));
for(i = 0; i < n; i++)
{
scanf("%s %d %d", list[i].month, &list[i].day, &list[i].year);
}
qsort(list, sizeof(list), sizeof(struct date), (compfn)sortDates);
for(i = 0; i < n; i++)
{
printf("%s %d %d\n", list[i].month, list[i].day, list[i].year);
}
}
编辑:所以我的排序工作正常,我只是在打印排序列表时努力将整数转换回月份的字符串表示形式。这是代码,我收到“数组下标不是整数”错误。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int (*compfn)(const void*, const void*);
struct date
{
int month;
int day; //The day of the month (e.g. 18)
int year; //The year of the date
};
char* months[]= {
"January", "February",
"March", "April",
"May", "June",
"July", "August",
"September", "October",
"November", "December"};
int getMonth(char tempMonth[])
{
int i = 0;
for(i = 0; i<12; i++)
{
if(tempMonth == months[i]) return i;
}
return 0;
}
char getStringMonth(struct date month)
{
return months[month];
}
int sortDates(struct date *elem1, struct date *elem2)
{
if (elem1 -> year < elem2 -> year)
{
return -1;
}
else
if (elem1->year > elem2->year)
{
return 1;
}
if ( elem1->month < elem2->month )
{
return -1;
}
else
if ( elem1->month > elem2->month )
{
return 1;
}
if ( elem1->day < elem2->day )
{list
return -1;
}
else
if ( elem1->day > elem2->day )
{
return 1;
}
else
return 0;
}
main()
{
int n;
int i;
char tempMonth[255]; //Used to store the month until checked
scanf("%d", &n);list
struct date *list;
list = (struct date *)malloc((n * sizeof(struct date)));
for(i = 0; i < n; i++)
{
scanf("%s %d %d", tempMonth, &list[i].day, &list[i].year);
list[i].month = getMonth(tempMonth);
}
qsort(list, sizeof(list), sizeof(struct date), (compfn)sortDates);
for(i = 0; i < n; i++)
{
printf("%s %d %d", getStringMonth(list[i].month), list[i].day, list[i].year);
}
}
【问题讨论】:
-
请不要那样做。如果您还有其他问题,请再问一个。