知識點:
邏輯表達式的靈活運用
法1:
switch()的用法,注意字符用 case 'a': ……;break; 數字用 case 6:……;break;
不要忘了break;
法2:
if……else 的用法
注意是否是閏年的算法
內容: 打印某年某月有幾天
輸入說明:
一行兩個整數,前面是年份 後面是月份
輸出說明:
一個整數
輸入樣例:
2009 6
輸出樣例 :
30
法1:
#include <stdio.h> int main() { int y,m; scanf("%d%d",&y,&m); if((y%4==0&&y%100!=0)||y%400==0) { switch (m) { case 1: printf("31\n");break; case 2: printf("29\n");break; case 3: printf("31\n");break; case 4: printf("30\n");break; case 5: printf("31\n");break; case 6: printf("30\n");break; case 7: printf("31\n");break; case 8: printf("31\n");break; case 9: printf("30\n");break; case 10: printf("31\n");break; case 11: printf("30\n");break; case 12: printf("31\n");break; } } else switch (m) { case 1: printf("31\n");break; case 2: printf("28\n");break; case 3: printf("31\n");break; case 4: printf("30\n");break; case 5: printf("31\n");break; case 6: printf("30\n");break; case 7: printf("31\n");break; case 8: printf("31\n");break; case 9: printf("30\n");break; case 10: printf("31\n");break; case 11: printf("30\n");break; case 12: printf("31\n");break; } return 0; }
法2:
#include <stdio.h> int main() { int y,m; scanf("%d%d",&y,&m); if (m==1||m==3||m==5||m==7||m==8||m==10||m==12) { printf("31\n"); } else { if (m==2) { if((y%4==0&&y%100!=0)||y%400==0) { printf("29\n"); } else { printf("28\n"); } } else { printf("30\n"); } } return 0; }
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,year);
c.set(Calendar.MONTH,month-1);//這個一定減1,也就是一月是0
c.set(Calendar.DAY_OF_MOUTH,day);
int result = c.get(Calendar.DAY_OF_YEAR);
1 注意scanf語句
2 getDate(y,days,&m,&d);
3 注意天數的計算swith()
4 getDate()函數
#include <stdio.h>
int isLeap(int year);
void getDate(int y,int days,int*pm,int *pd);
int getDays(int y,int m,int d);
int main (void)
{
int y,m,d,days;
printf("請輸入_年_月_日:\n");
scanf("%d%d%d",&y,&m,&d); //scanf語句的引號
days=getDays(y,m,d); //天數還應加d
printf("是%d年的第%d天:\n",y,days);
getDate(y,days,&m,&d);
printf("請輸入%d年%d月%d日:\n",y,m,d);
return 0;
}
//編寫子函數求某天是該年的幾月幾日
void getDate(int y,int days,int*pm,int *pd) /*y為年份,days為該年的某天,pm指向主調函數中存放某天的月值變量, */ /*pd指向主調函數中存放某天的日值變量*/
{
int m,d,i;
int day;
for(i=1;days>getDays(y,i,0);i++)
{
days=days-getDays(y,i,0);
}
m = i; /* m:某天計算後的月值 */
d = days; /* d:某天計算後的日值 */
*pm = m;
*pd = d;
}
//編寫子函數求某年某月某日是該年的第幾天
int getDays(int y,int m,int d)
{
int n=0;
switch(m)
{
case 12:
n+=30;
case 11:
n+=31;
case 10:
n+=30;
case 9:
n+=31;
case 8:
n+=31;
case 7:
n+=30;
case 6:
n+=31;
case 5:
n+=30;
case 4:
n+=31;
case 3:
if(isLeap(y)==1)
n+=29;
else
n+=28;
case 2:
n+=31;
case 1:
n+=d;
break;
default :
n+=d;
}
return n;
}
//編寫子函數判斷閏年。
int isLeap(int year)
{
if((year%4==0)&&(year%100!=0)||(year%400==0 ))
return 1;
else
return 0;......余下全文>>