输入年,输出该年每个月的天数。其中1,3,5,7,8,10,12月有31天,4,6,9,11有30天,2月有28天,闰年有29天。判断闰年的条件是:能被4整除但不能被100整除,或者能被400整除。
#include<>
int main()
{
int day,month,year;
scanf("%d",&year);
for(month=1;month<=12;month++){
switch(month)
{
case 2:
if(year%4=0&&year%100!=0||year%400==0)
{
day=29;
}else{
day=28;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day=31;
break;
case 4:
case 6:
case 9:
case 11:
day=30;
break;
}
printf("%d ",day);
}
return 0;
}
switch语句可以用来执行不同的代码块,具体取决于给定表达式的值。它的语法是
switch(表达式){case 常量1://执行的代码;break;
default://执行的代码(可选);break;}
在给定表达式的值于所列的case常量匹配时,switch语句会执行相关的代码块,并在执行完成后用break语句中断。如果没有case常量匹配,switch语句会执行default语句(如果存在)。
#include<>
int main()
{
int year,month,day;
printf("Please enter a year:");
scanf("%d",&year);
printf("\n");
for(month=1;month<=12;month++){
if(month==2){
if(year%400==0||year%4==0&&year%100!=0){
day=29;
}else{
day=28;
}
}
else if(month==4||month==6||month==9||month==11){
day=30;
}
else{
day=31;
}
printf("Month %d has %d days.\n",month,day);
}
printf("\n");
return 0;
}