一、问题分析与原理
计算月份天数的核心逻辑需解决两点:
- 闰年判断
根据格里高利历规则:
- 能被4整除但不能被100整除的年份 是闰年(如2024)
- 能被400整除的年份 也是闰年(如2000)
- 其他情况为平年
公式:(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
- 月份天数规则
- 31天:1月、3月、5月、7月、8月、10月、12月
- 30天:4月、6月、9月、11月
- 2月:闰年29天,平年28天
二、VS2019环境准备
创建C语言项目步骤:
- 新建项目
- 打开VS2019 → 选择“创建新项目” → 搜索“空项目”模板 → 设置名称(如MonthDays)和存储路径
- 添加源文件
- 右键“解决方案资源管理器”中的“源文件” → 选择“添加 → 新建项” → 命名文件为main.c(扩展名必须为.c)
- 配置编译器(首次使用时)
- 若报错“找不到stdio.h”,需安装C/C++开发组件:通过“工具 → 获取工具和功能” → 勾选“使用C++的桌面开发”
三、代码实现(两种方法)
方法1:数组存储法(推荐)
用数组存储各月默认天数,对闰年2月特殊处理- #include <stdio.h>
- // 判断闰年函数
- int is_leap_year(int year) {
- return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
- }
- // 计算月份天数
- int get_days(int year, int month) {
- int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 下标0占位,1-12对应月份
- if (month == 2 && is_leap_year(year))
- return 29; // 闰年2月
- else
- return days[month]; // 其他月份直接返回数组值
- }
- int main() {
- int year, month;
- printf("输入年份和月份(格式:年,月):");
- scanf("%d,%d", &year, &month); // 按逗号分隔输入
- if (month < 1 || month > 12) {
- printf("无效月份!\n");
- return 1; // 错误退出
- }
- printf("%d\n", get_days(year, month));
- return 0;
- }
复制代码 方法2:Switch语句法
通过switch分支处理不同月份- #include <stdio.h>
- int is_leap_year(int year) { /* 同上 */ }
- int get_days(int year, int month) {
- switch (month) {
- case 1: case 3: case 5: case 7: case 8: case 10: case 12:
- return 31;
- case 4: case 6: case 9: case 11:
- return 30;
- case 2:
- return is_leap_year(year) ? 29 : 28;
- default:
- return -1; // 无效月份标识
- }
- }
- int main() { /* 同上 */ }
复制代码两种方法对比
- 数组法:代码简洁,便于扩展(如增加月份校验)
- Switch法:逻辑直观,适合初学者理解分支结构
四、完整代码示例(数组法)
- #define _CRT_SECURE_NO_WARNINGS // 禁用VS安全警告
- #include <stdio.h>
- int is_leap_year(int year) {
- return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
- }
- int get_days(int year, int month) {
- int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- if (month < 1 || month > 12) return -1; // 月份无效
- if (month == 2 && is_leap_year(year)) return 29;
- return days[month];
- }
- int main() {
- int year, month;
- printf("输入年份和月份(格式:年,月):");
- if (scanf("%d,%d", &year, &month) != 2) { // 检测输入有效性
- printf("输入格式错误!\n");
- return 1;
- }
- int result = get_days(year, month);
- if (result == -1)
- printf("月份需在1-12之间!\n");
- else
- printf("%d\n", result);
-
- return 0;
- }
复制代码
五、运行与测试
- 编译运行
- 按Ctrl + F5(不调试运行)或F5(调试运行)
- 测试样例输入预期输出说明2018,831普通31天月份2020,229闰年2月2023,228平年2月2025,13错误提示无效月份处理
六、常见问题
- 输入逗号不生效?
- 检查scanf格式字符串是否为"%d,%d",确保输入时用逗号分隔(如2024,2)
- VS报错“scanf不安全”
- 在文件开头添加#define _CRT_SECURE_NO_WARNINGS
- 2月天数错误?
- 检查闰年判断逻辑是否遗漏% 400条件(如1900年不是闰年)
关键知识点复习
知识点要点闰年条件4整除且非100整除 或 400整除月份天数存储数组法:days[13]存储,下标1-12对应月份3
5
输入处理scanf("%d,%d", &year, &month) 匹配逗号分隔输入VS项目配置创建空项目 → 添加.c文件 → 确保扩展名为.c7
8
错误处理校验月份范围(1-12),返回-1标识无效输入此方案兼顾效率与可读性,适合学习和实际使用。通过数组法可快速扩展功能(如输出全年日历),而VS2019的工程化管理便于后续维护。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |