【项目:本月有几天?】
编程序,输入年份和月份,输出本月有多少天。合理选择分支语句完成设计任务。
样例输入1:2004 2
输出结果1:本月29天
样例输入2:2010 4
输出结果2:本月30天
[参考解答]
#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; } printf("%d 年 %d 月共有 %d 天。\n", year, month, days); return 0; }
有同学写出的代码如下。其缺点之一在于将程序写得太长了,不够简洁,再者,即使输入的月分不是2月,也要判断是否闰年,是不是做了多余的事?
#include <stdio.h> int main ( ) { int year, month, days; printf("请输入年、月: "); scanf("%d %d", &year, &month); if(year%4==0 && year%100!=0 ||year%400==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: days = 29; } } else //非闰年 { 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: days =28; } } printf("%d 年 %d 月共有 %d 天。\n", year, month, days); return 0; }
解法3:用if嵌套
#include <stdio.h> int main ( ) { int year, month, days; printf("请输入年、月: "); scanf("%d %d", &year, &month); if(month==2) { if((year%4==0 && year%100!=0)||(year%400==0)) days=29; else days=28; } else { if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) days=31; else { if(month==4 || month==6 || month==9 || month==11) days=30; } } printf("%d 年 %d 月共有 %d 天。\n", year, month, days); return 0; }