C语言:输入年份和月份,计算该月天数
C语言:输入年份和月份,计算该月天数
代码实现
以下是使用 C 语言编写的解决方案:c#include <stdio.h>
int isLeapYear(int year) { if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { return 1; // 是闰年 } else { return 0; // 不是闰年 }}
int getDaysOfMonth(int year, int month) { int days = 0;
switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if (isLeapYear(year)) { days = 29; } else { days = 28; } break; }
return days;}
int main() { int year, month; printf('请输入年份和月份,以空格分隔:'); scanf('%d %d', &year, &month);
int days = getDaysOfMonth(year, month); printf('%d年%d月有%d天
', year, month, days);
return 0;}
代码解释
-
isLeapYear(int year)函数:判断输入的年份是否为闰年。 - 根据闰年规则:能被 4 整除但不能被 100 整除,或能被 400 整除的年份为闰年。 - 返回 1 表示闰年,返回 0 表示平年。 -
getDaysOfMonth(int year, int month)函数:根据输入的年份和月份,返回该月的天数。 - 使用switch语句根据月份判断天数。 - 对于 2 月份,调用isLeapYear函数判断是否为闰年,从而确定天数。 -
main()函数:程序入口。 - 提示用户输入年份和月份。 - 调用getDaysOfMonth函数计算该月天数。 - 打印最终结果。
示例
输入:
2023 2
输出:
2023年2月有28天
原文地址: https://www.cveoy.top/t/topic/c8Mk 著作权归作者所有。请勿转载和采集!