C语言根据输入年份月份计算该月天数
C语言根据输入年份月份计算该月天数
本教程介绍如何使用C语言编写程序,实现根据用户输入的年份和月份,计算该月天数的功能。
代码示例c#include <stdio.h>
int main() { int year, month, days; printf('请输入年份和月份:'); scanf('%d%d', &year, &month);
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 ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { days = 29; } else { days = 28; } break; default: printf('输入的月份有误!
'); return 0; }
printf('%d年%d月有%d天。
', year, month, days); return 0;}
代码解释
- 包含头文件:
#include <stdio.h>引入标准输入输出库,用于使用printf和scanf函数。2. 定义变量: *year:存储用户输入的年份。 *month:存储用户输入的月份。 *days:存储计算得到的该月天数。3. 获取用户输入: 使用printf提示用户输入年份和月份,使用scanf读取用户输入并分别存储到year和month变量中。4. 使用switch语句判断月份: * 根据month的值,使用switch语句进行分支处理。 * 对于 1、3、5、7、8、10、12 月,将days赋值为 31。 * 对于 4、6、9、11 月,将days赋值为 30。 * 对于 2 月,需要判断是否为闰年: * 如果年份能被 4 整除但不能被 100 整除,或者能被 400 整除,则为闰年,将days赋值为 29。 * 否则为平年,将days赋值为 28。 * 如果输入的月份不在 1-12 之间,则输出错误信息并退出程序。5. 输出结果: 使用printf函数输出计算得到的该月天数。
总结
本教程介绍了如何使用 C 语言编写程序计算指定月份的天数,并对代码进行了详细解释。希望对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/gvgl 著作权归作者所有。请勿转载和采集!