C++从键盘输入年月,输出该月有多少天
作者:野牛程序员:2023-08-11 17:24:16 C++阅读 4010
以下是一个示例程序,展示了如何使用C++来从键盘输入年月,并输出该月有多少天:
#include <iostream>
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int main() {
int year, month;
std::cout << "请输入年份: ";
std::cin >> year;
std::cout << "请输入月份: ";
std::cin >> month;
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month < 1 || month > 12) {
std::cout << "输入的月份无效" << std::endl;
return 1;
}
if (isLeapYear(year) && month == 2) {
std::cout << year << "年" << month << "月有 29 天" << std::endl;
} else {
std::cout << year << "年" << month << "月有 " << daysInMonth[month - 1] << " 天" << std::endl;
}
return 0;
}在这个示例中,首先定义了一个 isLeapYear 函数,用于判断是否为闰年。然后,从用户输入获取年、月,并根据输入的年月输出该月有多少天。需要注意的是,根据是否为闰年来判断二月的天数。
请注意,这个示例仅适用于公历,对于其他历法(例如农历)可能需要更复杂的算法。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++输入年月日,判断是这年的第几天
- 下一篇:C++判断⽉份天数(判断闰年)
