下面是一个用 C++ 编写的函数,用于计算给定年份和月份的天数:
#include <iostream> int calculateDaysInMonth(int year, int month) { if (month < 1 || month > 12) { return -1; // 无效的月份 } int daysInMonth; if (month == 2) { &澳门一肖一码100精准王中王资料 nbsp; 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++ 编译器中,并运行它。用户需要输入年份和月份(以空格分隔),然后程序会输出该月的天数。
评论列表