標題:
202411新手1-生日快樂 (Birthday)
[打印本頁]
作者:
may
時間:
2024-12-25 23:13
標題:
202411新手1-生日快樂 (Birthday)
問題敘述
每年露露的生日都會大肆慶祝,要擁有一個完美的生日派對當然就要提早籌備,所以她想要一個倒數計時的小工具提醒她。 請撰寫一個程式可以輸入當前日期和生日,計算距離下一次生日還有幾天。(本題忽略閏年的情況,即二月固定為28天。)
輸入格式 第一列輸入兩個正整數,分別表示當前日期的月和日。
第二列輸入兩個正整數,分別表示生日的月和日。同一列的兩個整數間以空白間隔。
輸出格式 輸出一個整數,表示當前日期距離下一次生日還有幾天。
輸入範例1
1 1
1 2
輸出範例1
1
輸入範例2
9 7
9 6
輸出範例2
364
輸入範例3
12 25
12 25
輸出範例3
0
評分說明
此題目測資分為兩組,每組測資有多筆測試資料,需答對該組所有測資才能獲得該組分數,各組詳細限制如下。
第一組(40 分):今年的生日日期必定晚於當前日期(即下一次生日與當前日期在同一年)。
第二組(60 分):無特別限制。
作者:
may
時間:
2024-12-26 22:51
#include <bits/stdc++.h>
using namespace std;
// 定義每個月的天數
const int daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 計算從年初到指定日期的天數
int daysFromStartOfYear(int month, int day) {
int totalDays = 0;
for (int i = 0; i < month - 1; i++) {
totalDays += daysInMonth[i];
}
totalDays += day;
return totalDays;
}
int main() {
// 輸入當前日期
int currentMonth, currentDay;
cin >> currentMonth >> currentDay;
// 輸入生日
int birthdayMonth, birthdayDay;
cin >> birthdayMonth >> birthdayDay;
// 計算當前日期與生日的天數
int currentDays = daysFromStartOfYear(currentMonth, currentDay);
int birthdayDays = daysFromStartOfYear(birthdayMonth, birthdayDay);
// 總共有 365 天(忽略閏年)
const int totalDaysInYear = 365;
// 計算距離下一次生日的天數
int daysUntilBirthday;
if (birthdayDays >= currentDays) {
daysUntilBirthday = birthdayDays - currentDays;
} else {
daysUntilBirthday = totalDaysInYear - currentDays + birthdayDays;
}
// 輸出結果
cout << daysUntilBirthday << endl;
return 0;
}
複製代碼
--------------------------------------
說明
定義每月天數:
透過 daysInMonth 陣列定義每月的天數(固定為 28 天的 2 月,忽略閏年)。
計算天數:
使用函式 daysFromStartOfYear,累加從 1 月 1 日到指定日期的總天數。
處理輸入:
程式從標準輸入讀入兩組日期,分別為當前日期和生日。
計算距離:
比較當前日期與生日的天數,分成兩種情況:
若生日在當前日期之後或當天,直接相減即可。
若生日已過,需計算今年剩餘天數加上下一年生日的天數。
輸出結果:
將計算的結果輸出,表示距離下一次生日的天數。
測試範例
範例 1
輸入:
1 1
1 2
輸出:
1
範例 2
輸入:
9 7
9 6
輸出:
364
範例 3
輸入:
12 25
12 25
輸出:
0
特點
簡單易懂的邏輯,適合初學者學習。
使用固定陣列來管理每月天數,忽略閏年的情況。
處理全年任何兩個日期間的天數差異。
歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://istak.org.tw/seed/)
Powered by Discuz! 7.2