输出一个万年历
C#代码
1 static void Date(int year) 2 { 3 int lastDays = 0;//定义一个偏移量用来计算每个月的第一天是星期几 4 5 for (int i = 1900; i < year; i++)//1900年1月1日正好是星期一 6 { 7 if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)//判断闰年,给偏移赋值 8 { 9 lastDays += 366; 10 } 11 else 12 { 13 lastDays += 365; 14 } 15 } 16 17 for (int j = 1; j <= 12; j++)//用for循环打印每个月份 18 { 19 //判断每个月的第一天是星期几(前面有多少空格) 20 int weekSpace = lastDays % 7; 21 //每个月的天数 22 int monthDays = 0; 23 24 //输出表头 25 if (j < 10) 26 Console.WriteLine("===========0" + j + "月" + "==========="); 27 else 28 Console.WriteLine("===========" + j + "月" + "==========="); 29 Console.WriteLine("一 " + "二 " + "三 " + "四 " + "五 " + "六 " + "日 "); 30 31 //输出每个月第一天前面的空位 32 for (int m_weekSpace = 1; m_weekSpace <= weekSpace; m_weekSpace++) 33 Console.Write(" "); 34 35 switch (j)//判断当月天数 36 { 37 case 1: case 3: case 5: case 7: case 8: case 10: case 12: 38 monthDays = 31; break; 39 case 4: case 6: case 9: case 11: 40 monthDays = 30; break; 41 case 2: 42 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)//判断闰年,给偏移赋值 43 { 44 monthDays = 29; 45 break; 46 } 47 else 48 { 49 monthDays = 28; 50 break; 51 } 52 } 53 54 //打印每一天 55 for (int m_monthDays = 1; m_monthDays <= monthDays; m_monthDays++) 56 { 57 //控制排版 58 if (m_monthDays < 10) 59 { 60 //判断当前天的下一天是否星期一(是否换行) 61 if ((m_monthDays + weekSpace) % 7 == 0 && (m_monthDays + weekSpace) >= 7) 62 Console.WriteLine("0" + m_monthDays); 63 else 64 Console.Write("0" + m_monthDays + " "); 65 } 66 else 67 { 68 if ((m_monthDays + weekSpace) % 7 == 0 && (m_monthDays + weekSpace) >= 7) 69 Console.WriteLine(m_monthDays); 70 else 71 Console.Write(m_monthDays + " "); 72 } 73 } 74 Console.WriteLine(); 75 Console.WriteLine(); 76 lastDays += monthDays; 77 } 78 }
打印结果: