1.简要介绍
1.这是一个比较完整的输入月份与年份给出天数的c语言代码。添加了函数注释提高可读性。减少了if-else结构保证简洁性。给出了输入格式提示和错误输入报错以及反馈。
2.注意
采用visual studio编写,所以采用scanf_s读取输入。
#include <stdio.h>
#include <stdbool.h>
// 根据月份和年份确定该月有多少天
int days_of_month(int month, int year) {
int day_array[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) ? 29 : day_array[month - 1];
}
// 判断给定年份是否是闰年
bool is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int main(void) {
int month, year;
char input[100];
bool continue_loop = true;
printf("请输入月份和年份 (MM/YYYY): \n");
fgets(input, sizeof(input), stdin);//读取防止第一次输入不显示结果
while (continue_loop) {
if (sscanf_s(input, "%d/%d", &month, &year) != 2 || month < 1 || month > 12 || year < 1) {
printf("无效输入,请重试。\n");
}
else {
printf("总天数: %d\n", days_of_month(month, year));
}
printf("请输入月份和年份 (MM/YYYY): \n");
// 读取下一次输入
fgets(input, sizeof(input), stdin);
// 判断是否需要结束循环
continue_loop = (input[0] != '\n');
}
return 0;
}