C++第9周项目4参考——本月有几天?

课程首页地址:http://blog.csdn.net/sxhelijian/article/details/7910565

【项目4:本月有几天?】输入年、月,输出本月有多少天。合理选择分支语句完成设计任务。

输入样例1:2004 2
输出结果1:本月29天
输入样例2:2010 4
输出结果2:本月30天


参考解答:

#include<iostream>
using namespace std; 
int main()  
{  
	int  year, month, days;  
	cout << "请输入年、月: ";
	cin >> 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;
	}
	cout<<year<<"年"<<month<<"月共有"<<days<<"天。"<<endl;
	return 0;  
}  

有同学写出的代码如下。其缺点之一在于将程序写得太长了,不够简洁,再者,即使输入的月分不是2月,也要判断是否闰年,是不是做了多余的事?

#include<iostream>
using namespace std; 
int main()  
{  
	int  year, month, days;  
	cout << "请输入年、月: ";
	cin >> 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:
		case 12:
			days = 30;
			break;
		case 2:
			days =28;
		}
	}
	cout<<year<<"年"<<month<<"月共有"<<days<<"天。"<<endl;
	return 0;  
}  

有位同学的解答如下:

#include <iostream>
using namespace std;
int main ()
{
	int year,month;
	cout<<"                     您正在使用的是日历表"<<endl;
	cout<<"请输入年份:"<<endl;
	cin>>year;
	cout<<"请输入月份:"<<endl;
	cin>>month;
	if((year%4==0  &&  year%100!=0)||(year%400==0))
	{
		if(month==2)
			cout<<"本月有29天";
		if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
			cout<<"本月有31天";
		if(month==4 || month==6 || month==9 || month==11)
			cout<<"本月有30天";
	}
	else
	{
		if(month==2)
			cout<<"本月有28天";
		if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
			cout<<"本月有31天";
        if(month==4 || month==6 || month==9 || month==11)
			cout<<"本月有30天";
	}
	return 0;
}
这种思路不错,但存在的问题是:(1)即使不是2月,也要判断闰年,多余了;(2)即使已经是2月了,并且进行了正确的赋值,一些比较仍然要做,用不着。

据此,改进的程序是:

#include <iostream>
using namespace std;
int main ()
{
	int year,month,days;
	cout<<"                     您正在使用的是日历表"<<endl;
	cout<<"请输入年份:"<<endl;
	cin>>year;
	cout<<"请输入月份:"<<endl;
	cin>>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;
		}
	}
	cout<<"本月有"<<days<<"天"<<endl;
	return 0;
}



原文地址:https://www.cnblogs.com/hehe520/p/6142667.html