思路:将年历拆分为12个月历实现
在每个月历中,判断每个月的天数,同时通过年月日判断星期数,每逢周六换行打印输出。其中对于2月,需要判断是否为闰年。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Days03
{
internal class Program
{
//判断月的天数
private static int countDaysOfMonth(int year,int mouth)
{
int count = 0;
switch (mouth)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
count = 31;
break;
case 4:
case 6:
case 9:
case 11:
count = 30;
break;
case 2:
count = runYearOrPin(year);
break;
}
return count;
}
//判断是否闰年
private static int runYearOrPin(int year)
{
if(year%400==0||(year%4==0&&year%100!=0))
{
return 29;
}
else
{
return 28;
}
}
//判断是否闰年方法2
private static bool leapYear(int year)
{
return (year % 400 != 0 && (year % 4 == 0 && year % 100 != 0));
}
//根据年月日计算星期几
/// <summary>
/// 根据年月日计算星期数的方法
/// </summary>
/// <param name="year">年数</param>
/// <param name="month">月数</param>
/// <param name="day">天数</param>
/// <returns></returns>
private static int GetWeekByDay(int year,int month,int day)
{
DateTime dt = new DateTime(year, month, day);
return (int)dt.DayOfWeek;
}
//控制台实现月历
private static void monthOutput(int year, int month)
{
//表头
Console.WriteLine("{0}年{1}月", year, month);
Console.WriteLine("日\t一\t二\t三\t四\t五\t六\t");
Console.WriteLine("\n");
//计算每月1号星期几 输出空格
int week = GetWeekByDay(year, month, 1);
for (int i = 1;i<= week;i++)
{
Console.Write("\t");
}
//计算当月天数 输出1 2 3....
int days = countDaysOfMonth(year, month);
for(int i=1;i<=days;i++)
{
Console.Write(i + "\t");
//每逢周六换行
if(GetWeekByDay(year,month,i)==6)
{
Console.WriteLine("\n");
}
}
Console.WriteLine("\n");
}
//打印年历
private static void printYearCalendar(int year)
{
for(int i=1;i<=12;i++)
{
monthOutput(year, i);
}
}
static void Main()
{
Console.WriteLine("请输入年份:");
int year = int.Parse(Console.ReadLine());
printYearCalendar(year);
}
}
}