C++ 获取指定月份天数的代码示例
以下是使用 C++ 编写的代码示例,用于获取指定年份和月份的天数:
#include <iostream>
int getDaysInMonth(int year, int month) {
int days;
switch (month) {
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
days = 31;
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
days = 30;
break;
case 2: // February
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
default:
days = -1; // Invalid month
break;
}
return days;
}
int main() {
int year, month;
std::cout << '请输入年份和月份:' << std::endl;
std::cin >> year >> month;
int daysInMonth = getDaysInMonth(year, month);
if (daysInMonth == -1) {
std::cout << '无效的月份' << std::endl;
} else {
std::cout << '该月份的天数为:' << daysInMonth << std::endl;
}
return 0;
}
你可以在代码中输入年份和月份,然后程序将输出该月份的天数。
希望这个 C++ 代码对你有帮助!如果你还有其他问题,请随时提问。
原文地址: http://www.cveoy.top/t/topic/9z1 著作权归作者所有。请勿转载和采集!