求:同日出生的人的總個數,請使用面向對象的方法,找出若干同學中,生日相同的學生總數。
提示:
1、定義類表示日期,包含私有屬性年月日,重載等於操作符,用於大小比較
2、定義類表示學生,包含私有屬性姓名、生日(日期類型)
輸入:四個學生對象的信息,分別是姓名,年,月,日
比如 XiaoZhang 1994 5 1
XiaoWang 1994 5 1
XiaoLi 1994 6 3
XiaoChen 1994 6 3
輸出 生日相同的學生總數
比如 4
關鍵是不知道用C怎麼做?求算法的思路??
好吧。可能我寫代碼也上瘾了。
#include <stdio.h>
#define MAXSTUDENTS 200
typedef struct
{
char* name;
int year;
int month;
int day;
int birthday;
} stutype;
typedef struct
{
stutype stu[MAXSTUDENTS];
int count;
} stulist;
stutype assign(char* name, int year, int month, int day);
stulist sort(stulist list);
main()
{
stulist list;
int n = 1;
int i;
int differ = 1;
list.stu[0] = assign("XiaoZhang", 1994, 5, 1);
list.stu[1] = assign("XiaoLi", 1994, 6, 3);
list.stu[2] = assign("XiaoWang", 1994, 5, 1);
list.stu[3] = assign("XiaoChen", 1994, 6, 3);
list.stu[4] = assign("XiaoDong", 1994, 8, 1);
list.stu[5] = assign("XiaoMing", 1994, 3, 3);
list.stu[6] = assign("XiaoFang", 1994, 5, 1);
list.count = 7;
list = sort(list);
for ( i = 0; i < list.count - 1; i++)
{
if ( list.stu[i + 1].birthday == list.stu[i].birthday)
{
n += 1;
differ = 0;
}
else if ( differ == 0)
{
n +=1;
differ += 1;
}
}
if ( differ != 0) // 多加了一次,去掉
n -= 1;
for ( i = 0; i < list.count; i++)
printf("%s, %d\n", list.stu[i].name, list.stu[i].birthday);
printf("生日相同的學生總數:%d.\n", n);
}
stutype assign(char* name, int year, int month, int day)
{
stutype student;
student.name = name;
student.year = year;
student.month = month;
student.day = day;
student.birthday =
student.year * 10000 + student.month * 100 + student.day;
return student;
} // 學生結構賦值
stulist sort(stulist list)
{
stutype temp;
int i;
int j;
int finish = 0;
for ( i = 0; i < list.count - 1 && finish == 0; i++)
{
finish = 1;
for ( j = 0; j < list.count - 1; j++)
if ( list.stu[j].birthday > list.stu[j + 1].birthday)
{
temp = list.stu[j];
list.stu[j] = list.stu[j + 1];
list.stu[j + 1] = temp;
finish = 0;
}
}
return list;
} // 冒泡排序