1.用户输入年和月,用switch语句实现显示该月有多少天

2024-11-15 11:44:24
推荐回答(2个)
回答(1):

#include
#include

main()
{
int a,b;
printf("please enter the data\n");
scanf("%d,%d",&a,&b);
switch(b)
{
case 1:printf("%d year %d month have 31 days\n",a,b);
break;
case 2:
if((year % 400 == 0)||(year % 4 == 0)&&(year % 100 != 0))
{
printf("%d year %d month have 29 days\n",a,b);
}
else
printf("%d year %d month have 28 days\n",a,b);
break;
case 3:printf("%d year %d month have 31 days\n",a,b);
break;
case 4:printf("%d year %d month have 30 days\n",a,b);
break;
case 5:printf("%d year %d month have 31 days\n",a,b);
break;
case 6:printf("%d year %d month have 30 days\n",a,b);
break;
case 7:printf("%d year %d month have 31 days\n",a,b);
break;
case 8:printf("%d year %d month have 31 days\n",a,b);
break;
case 9:printf("%d year %d month have 30 days\n",a,b);
break;
case 10:printf("%d year %d month have 31 days\n",a,b);
break;
case 11:printf("%d year %d month have 30 days\n",a,b);
break;
case 12:printf("%d year %d month have 31 days\n",a,b);
break;
default:printf("error\n");

}
}
注意年和月之间用逗号分开;经VC测试 程序可行

回答(2):

#include
/**
* 输入年份和月来统计当月有多少天
*/
bool isleapYear(int year){
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return true;
else
return false;
}
int getDays(int year,int month){
int day = 0;
if(month < 8){
for(int i = 1;i <= 7;i++){
if(month == i){
if(i % 2 == 0){
if(i == 2){
if(isleapYear(year))
day = 29;
else
day = 28;
}else{
day = 30;
}
}else{
cout<<"hello";
day = 31;
}
break;
}

}
}else{
for(int i = 8;i <= 12;i++){
if(month == i){
if(i % 2 == 0){
day = 31;
}else{
day = 30;
}
break;
}
}
}
return day;
}
int dayOfMonth(int year,int month){
return getDays(year,month);
}

int main(){
int year,month;
cout<<"请分别输入年份和月分:\n";
cin>>year>>month;
int days = dayOfMonth(year,month);
cout< return 0;
}