假如现在让你写一个程序,要求是用户输入年份和月份,输出这个月有几天。你怎么写?我猜新手大部分应该是以下两种
- if 嵌套
#include<stdio.h>
int main() {
int year, month;
while (1) {
//得到用户输入的数据
printf("请输入年份和月份:");
scanf_s("%d.%d", &year, &month);
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) {
printf("这个月有31天\n");
}if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400)) == 0)
//条件成立为闰年,则二月份有29天
printf("这个月有29天\n");
else
//条件成立为平年,则二月份有28天
printf("这个月有28天\n");
}else {
printf("这个月有30天\n");
}
}
}
- switch
#include<stdio.h>
int main() {
int year, month;
while (1) {
//得到用户输入的数据
printf("请输入年份和月份:");
scanf_s("%d.%d", &year, &month);
switch (month) {
case 1:
printf("这个月有31天\n");
case 2:
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
//条件成立为闰年,则二月份有29天
printf("这个月有29天\n");
break;
}
else
//条件成立为平年,则二月份有28天
printf("这个月有28天\n");
break;
}
case 3:
printf("这个月有31天\n");
break;
case 4:
printf("这个月有30天\n");
break;
case 5:
printf("这个月有31天\n");
break;
case 6:
printf("这个月有30天\n");
break;
case 7:
printf("这个月有31天\n");
break;
case 8:
printf("这个月有31天\n");
break;
case 9:
printf("这个月有30天\n");
break;
case 10:
printf("这个月有31天\n");
break;
case 11:
printf("这个月有30天\n");
break;
case 12:
printf("这个月有31天\n");
break;
}
}
}
上面两种代码的程序复杂度太高了,所以下面用数组的方式进行简化。
代码:
#include<stdio.h>
int leap_year(int year,int month);
int main() {
int year, month;
while (1) {
//得到用户输入的数据
printf("请输入年份和月份:");
scanf_s("%d.%d", &year, &month);
int days[12] = { 31,leap_year(year,month),31,30,31,30,31,31,30,31,30,31 };
printf("这个月有%d天\n",days[month-1]);
}
}
/*
函数作用:判断这一年是否为闰年
参数:年份和月份
返回值:是闰年返回29,不是则返回28
*/
int leap_year(int year,int month) {
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 29;
}else
return 28;
}
}
运行结果:
总结
这样写的话只用到了一个 if 判断,用数组的方式存储了每个月份的天数。这种方式就是表驱动法。有时 if else 逻辑层太多,用数组替代,逻辑层将会变得非常简单。