c++编写一个函数计算一个月有几天
作者:野牛程序员:2023-08-11 17:28:30 C++阅读 3603
下面是一个用 C++ 编写的函数,用于计算给定年份和月份的天数:
#include <iostream>
int calculateDaysInMonth(int year, int month) {
if (month < 1 || month > 12) {
return -1; // 无效的月份
}
int daysInMonth;
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
daysInMonth = 29; // 闰年2月有29天
} else {
daysInMonth = 28; // 平年2月有28天
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30; // 四月、六月、九月、十一月有30天
} else {
daysInMonth = 31; // 其他月份有31天
}
return daysInMonth;
}
int main() {
int year, month;
std::cout << "请输入年份和月份(用空格分隔):";
std::cin >> year >> month;
int days = calculateDaysInMonth(year, month);
if (days == -1) {
std::cout << "无效的月份" << std::endl;
} else {
std::cout << year << "年" << month << "月有" << days << "天" << std::endl;
}
return 0;
}可以将上面的代码粘贴到 C++ 编译器中,并运行它。用户需要输入年份和月份(以空格分隔),然后程序会输出该月的天数。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C++判断⽉份天数(判断闰年)
- 下一篇:c++什么是递归函数
