# Function
## 引言
> Q. (親愛的chatGPT...)請幫我撰寫一個C\++程式,輸入西元年月日,以及經過多少天,可以輸出相應的西元年月日。
> A. 以下是一個C++程式,可以根據輸入的西元年月日和經過的天數,計算出相應的新的西元年月日。
:::warning
- 觀察主程式,使用的自訂函式,輸入、輸出分別為何?
- 走進這個自訂函式,它又使用了哪些自訂函式,他們的輸入、輸出分別為何?
- 為什麼要有這些自訂函式呢?他們分別反映出,這題在增加天數的時候,需要考量哪些可能?
:::
::: spoiler 點我看完整程式碼
```cpp=
// 判斷是否為閏年的函數
bool isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
} else {
return false;
}
}
// 計算每個月的天數
int daysInMonth(int year, int month) {
switch (month) {
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
return 31;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
return 30;
case 2: // February
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
default:
return -1; // 如果月份不在1-12範圍內,返回錯誤碼
}
}
// 計算新的日期
void calculateNewDate(int year, int month, int day, int daysToAdd,
int& newYear, int& newMonth, int& newDay) {
// 先把原來的日期加上經過的天數
newYear = year;
newMonth = month;
newDay = day + daysToAdd;
// 當新的日期超過了當月的天數,需要進行日期調整
while (newDay > daysInMonth(newYear, newMonth)) {
newDay -= daysInMonth(newYear, newMonth); // 減去本月天數
newMonth++; // 月份加一
// 如果月份超過12,則進入新的一年
if (newMonth > 12) {
newMonth = 1; // 月份歸1
newYear++; // 年份加一
}
}
}
int main() {
int year, month, day;
int daysToAdd;
// 輸入西元年月日和經過的天數
std::cout << "請輸入西元年份: ";
std::cin >> year;
std::cout << "請輸入月份: ";
std::cin >> month;
std::cout << "請輸入日期: ";
std::cin >> day;
std::cout << "請輸入經過的天數: ";
std::cin >> daysToAdd;
int newYear, newMonth, newDay;
// 計算新的日期
calculateNewDate(year, month, day, daysToAdd, newYear, newMonth, newDay);
// 輸出結果
std::cout << "新的日期為: " << newYear << "年" << newMonth << "月" << newDay << "日" << std::endl;
return 0;
}
```
:::
### FAQ
**Q. 這個函式的`&`在幹嘛?**
```cpp=
void calculateNewDate(int year, int month, int day, int daysToAdd, int& newYear, int& newMonth, int& newDay)
```
A. 這是==傳參考==的用法,歡迎搶先閱讀==3 - 1 指標與函式==。
**Q. 可以傳陣列到函式裡面嗎?**
A. 需要瞭解一些原理和規則,歡迎搶先閱讀==3 - 2 指標與陣列==。