C++编程:给出年、月、日,计算该日是该年的第几天。

用swich语句

#include<iostream>
using namespace std;

bool LeapYear(int year){ //判断是否为闰年,是则返回true,不是则返回false
int a,b,c;
a=year%4;
b=year%100;
c=year%400;
if ((c==0)||(b!=0)&&(a==0))
return true;
else
return false;
}
int main()
{
int year,month,day,total=0;
cout<<"请输入年 月 日"<<endl;
cin>>year>>month>>day;
//先计算该月之前的天数,假如输入的月份是7,那么通过case语句算出前6个月的天数,再加上day
switch(month-1) //因此这里需month-1
{
case 11:total +=30;
case 10:total +=31;
case 9:total +=30;
case 8:total +=31;
case 7:total +=31;
case 6:total +=30;
case 5:total +=31;
case 4:total +=30;
case 3:total +=31;
case 2:LeapYear(year)?total +=29:total +=28; //闰年29天,平年28天
case 1:total +=31;
case 0:total +=0;
default:total +=day;
}
cout<<"该天是"<<year<<"年的第"<<total<<"天"<<endl;
return 0;
}

不知道你对case语句的程序流程了解多少。
提示一句:在执行switch语句时,根据switch表达式的值找到与之匹配的case子句,就从此case子句开始执行下去,不再进行判断。
(当然如果加上break就不一样了)
不懂再问,还是很简单的程序
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-10-14
#include<iostream>
using namespace std;
int d[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31} };
int days(int m,int a=0)
{
int sumday=0;
for(int i=0;i<m-1;++i)
sumday+=d[a][i];
return sumday;
}
int main()
{
int day=0,month=0,year=0;
cout<<"day :";cin>>day;
cout<<"month :";cin>>month;
cout<<"year :";cin>>year;
int a=0;
if((year%4==0&&year%100!=0)||year%400==0)a=1;
switch(month)
{
case 1:case 2:
case 3:case 4:
case 5:case 6:
case 7:case 8:
case 9:case 10:
case 11:case 12: cout<<days(month,a)+day<<endl;
default: break;
}
}
有点牵强,把switch去掉更简洁点,本回答被提问者采纳
第2个回答  2009-10-14
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

bool leapYear(int year)
{

if (year%4==0 && year%100!=0)
return true;
if (year%400==0)
return true;
return false;
}
void main()
{
int year,month,day;
int MonthDay[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

while (true)
{
cout<<"请输入年(0~3000)、月(1~12)、日(1~月份而定): "<<endl;
cin>>year>>month>>day;
if (cin.good() && (year>=0&&year<=3000) && (month>=1&&month<=12)
&& (day>=1&&day<=MonthDay[month]))
{
break;
}
cout<<"输入有误,";
cin.clear();
cin.sync();
}
cout<<year<<"年"<<month<<"月"<<day<<"日是该年的第 ";

switch(month)
{
case 12:day+=30;
case 11:day+=31;
case 10:day+=30;
case 9:day+=31;
case 8:day+=31;
case 7:day+=30;
case 6:day+=31;
case 5:day+=30;
case 4:day+=31;
case 3:day+=((leapYear(year))?29:28);
case 2:day+=31;
case 1:break;
default: cout<<"Exception!"<<endl;
}

cout<<day<<" 天!"<<endl;
}
相似回答