cpp练习:最小生日差值计算(运算符重载)

题目描述

定义一个学生类Student,包含该学生的姓名、出生年、月、日 ,重定义 “-”号实现两个学生之间相差多少天的比较。并利用重载的“-”运算符,求所有学生中年龄相差最小的两个人的名字以及相差天数。

输入

第一行:输入所需要输入的学生个数;
第二行开始,依次输入每个学生的姓名、出生年、月、日。

输出

输出年龄相差最小的两个人的名字以及相差天数,名字的输出顺序按输入的先后,天数大于等于0。

输入样例

3
Tom 1995 1 1
Joe 1995 2 28
Jimmy 1996 1 8

输出样例

Tom和Joe年龄相差最小,为58天。

参考代码

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

class Student {
private:
	string name;
	int year, month, day;
public:
	Student(string n, int y, int m, int d) :name(n), year(y), month(m), day(d) {}

	string getName() {
		return name;
	}

	bool isLeapYear(int year) {
		return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
	}

	int getTotalDays() {
		int days = 0;

		//公式,详见下方笔记
		days += (year - 1) * 365;
		days += (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;

		//当年完整月份的天数
		static const int daysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		for (int m = 1; m < month; ++m) {
			days += daysInMonth[m];
		}

		//如果是闰年且月份大于2月,则需要额外加1天
		if (month > 2 && isLeapYear(year)){
			days += 1;
		}

		//当月的天数
		days += day;
		return days;
	}

	int operator-(Student& other) {
		int days1 = getTotalDays();
		int days2 = other.getTotalDays();
		return abs(days1 - days2);
	}
};

int main() {
	int n;
	cin >> n;
	vector<Student>stu;
	string name;
	int y, m, d;
	for (int i = 0; i < n; ++i) {
		cin >> name >> y >> m >> d;
		stu.emplace_back(name, y, m, d);
	}

	int min = INT_MAX;
	int diff;
	string n1, n2;
	for (int i = 0; i < n; ++i) {
		for (int j = i + 1; j < n; ++j) {
			diff = stu[i] - stu[j];
			if (diff < min) {
				min = diff;
				n1 = stu[i].getName();
				n2 = stu[j].getName();
			}
		}
	}
	cout << n1 << "和" << n2 << "年龄相差最小,为" << min << "天。" << endl;
	return 0;
}

笔记

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值