定义结构体,输入两个同学的信息,比较两个同学的生日,输出生日较大同学的全部信息,生日包括年月日
时间: 2023-12-11 09:04:35 浏览: 31
好的,这里是C++语言的代码实现,其中我们将生日的年、月、日分别用三个整数来表示:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义日期结构体
struct Date {
int year; // 年
int month; // 月
int day; // 日
};
// 定义学生结构体
struct Student {
string name; // 姓名
int age; // 年龄
Date birthday; // 生日
};
int main() {
// 输入第一个学生的信息
Student stu1;
cout << "请输入第一个学生的姓名:";
getline(cin, stu1.name);
cout << "请输入第一个学生的年龄:";
cin >> stu1.age;
cout << "请输入第一个学生的生日(如2021 01 01表示2021年1月1日):";
cin >> stu1.birthday.year >> stu1.birthday.month >> stu1.birthday.day;
cin.ignore(); // 必须加上这一行,否则下一个getline会读取回车符
// 输入第二个学生的信息
Student stu2;
cout << "请输入第二个学生的姓名:";
getline(cin, stu2.name);
cout << "请输入第二个学生的年龄:";
cin >> stu2.age;
cout << "请输入第二个学生的生日(如2021 01 01表示2021年1月1日):";
cin >> stu2.birthday.year >> stu2.birthday.month >> stu2.birthday.day;
// 比较两个学生的生日
if (stu1.birthday.year > stu2.birthday.year ||
(stu1.birthday.year == stu2.birthday.year &&
(stu1.birthday.month > stu2.birthday.month ||
(stu1.birthday.month == stu2.birthday.month &&
stu1.birthday.day > stu2.birthday.day)))) {
// 输出生日较大的学生的全部信息
cout << "生日较大的学生是:" << endl;
cout << "姓名:" << stu1.name << endl;
cout << "年龄:" << stu1.age << endl;
cout << "生日:" << stu1.birthday.year << "年" << stu1.birthday.month << "月" << stu1.birthday.day << "日" << endl;
} else {
// 输出生日较大的学生的全部信息
cout << "生日较大的学生是:" << endl;
cout << "姓名:" << stu2.name << endl;
cout << "年龄:" << stu2.age << endl;
cout << "生日:" << stu2.birthday.year << "年" << stu2.birthday.month << "月" << stu2.birthday.day << "日" << endl;
}
return 0;
}
```
同样,这只是一个简单的示例,实际应用中可能需要更复杂的结构体和更丰富的功能。