0
点赞
收藏
分享

微信扫一扫

日历代码

大体可以分为4个方法,第一个方法判断是否为闰年,第二个方法判断某月的天数,第三个方法判断某一天在星期几,第四个方法输出整个月历(结合以上三个方法),最后在 Main方法中被调用

```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day03
{
class Program
{
static void Main(string[] args)
{
Calendar(2022);
}
/// <summary>
/// 判断是否为闰年
/// </summary>
/// <param name="year">年份</param>
/// <returns>bool值</returns>
private static bool RunYear(int year)
{
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
/// <summary>
/// 判断某月的天数
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns>月份的天数</returns>
private static int MonthDay(int year, int month)
{
if (month == 2)
{
if (RunYear(year))
return 29;
else
return 28;
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
else
return 31;
}
/// <summary>
/// 判断某天在星期几
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <param name="day">天数</param>
/// <returns>该天在星期几</returns>
private static int GetDayOfWeek(int year, int month, int day)
{
DateTime dt = new DateTime(year, month, day);
return (int)dt.DayOfWeek;
}
/// <summary>
/// 输出年历
/// </summary>
/// <param name="year">年份</param>
private static void Calendar(int year)
{
Console.WriteLine("\t\t年份为{0}的日历",year);
for (int i = 1; i <= 12; i++)
{
Console.WriteLine("\t\t\t{0}月",i);
Console.WriteLine("日\t一\t二\t三\t四\t五\t六");
int days = MonthDay(year, i);
int week = GetDayOfWeek(year, i, 1);
for (int k = 0; k < week; k++)
Console.Write('\t');
for (int j = 1; j <= days; j++,week++)
{
Console.Write(j + "\t");
if (week % 7 == 6)
Console.WriteLine();
}
Console.WriteLine();
}
}
}
}


::: hljs-center

## 输出结果为:

:::

![image.png](https://s2.51cto.com/images/20220629/1656471656713054.png?x-oss-process=image/watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)
## ==注意点:输出月历的时候(第四个方法),要先输出应该有的空格,然后再一天一天的输出,遇到周六要换行==
举报

相关推荐

0 条评论