实现输出一个年份后,输出这个年份的月份、星期、日期;
提示:1900.1.1刚好是星期一。
编码工具:VS2015
下面是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 万年历
{
class Program
{
static void Main(string[] args)
{
Console.Write("请输入你要查询的年份:");
int currentYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
int x, y;
for (int i = 1; i <=12; i++)//遍历每个月
{
x = WhatDay(currentYear, i);//得出某年某月的第一天是星期几
y = EveryMonthDays(currentYear, i);//得出某年某月的天数
int index;//计数器
Console.WriteLine(" {0}年{1}月\n", currentYear, i);
Console.WriteLine("一 二 三 四 五 六 日");
Console.WriteLine("---------------------------------");
index = x;
int monthIndex2 = 1;//每个月默认从第一天开始
while (monthIndex2<=y)
{
for (int j = 1; j < index; j++)
{
Console.Write(" " + " ");
}
for (int k = index; k <=7; k++)
{
if (monthIndex2>y)
{
break;
}
if (monthIndex2<=9)
{
Console.Write(" " + monthIndex2 + " ");
}
else
{
Console.Write(monthIndex2 + " ");
}
monthIndex2++;
}
Console.WriteLine();
index = 1;
}
Console.WriteLine("\n\n");
}
Console.ReadKey();
}
static bool IsLeapYear(int year)//判断某年是不是闰年
{
if (year%4==0&&year%100!=0||year%400==0)
{
//Console.WriteLine("是 闰年");
return true;
}
else
{
//Console.WriteLine("不是 闰年");
return false;
}
}
static int WhatDay(int currentYear,int month)//判断从某年某月第一天是星期几
{
int num;
int totalDays = 0;
for (int i = 1900; i < currentYear; i++)
{
if (IsLeapYear(i))
{
totalDays += 366;
}
else
{
totalDays += 365;
}
}
for (int j = 1; j < month; j++)
{
totalDays += EveryMonthDays(currentYear, j);
}
num = totalDays % 7;
return num + 1;
}
static int EveryMonthDays(int year, int month)//判断某年每个月的天数
{
int i = month;
int monthDay;
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
{
monthDay = 31;
}
else if (i == 4 || i == 6 || i == 9 || i == 11)
{
monthDay = 30;
}
else if (i == 2 && IsLeapYear(year) == true)
{
monthDay = 29;
}
else
{
monthDay = 28;
}
return monthDay;
}
}
}