(1) // 在控制台中提示用户首先输入一个年份,在提示用户输入一个月份,根据用户输入的年份月份输出这个月有多少天(需要判断是否是闰年)
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please input the year:");
int year = Int32.Parse(Console.ReadLine());
if (year > 0)
{
Console.WriteLine("please input the Month:");
int month = Int32.Parse(Console.ReadLine());
if (month > 0 && month < 13)
{
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: Console.WriteLine("31");
break;
case 2:
if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0)
{
Console.WriteLine("29");
}
else
{
Console.WriteLine("28");
}
break;
case 4:
case 6:
case 9:
case 11:
Console.WriteLine("30");
break;
}
}
else
{
Console.WriteLine("please input the correct Month!");
}
}
else
{
Console.WriteLine("please input the correct year!");
}
Console.ReadKey();
}
}
}
(2) 根据输入的年月日 判断那天是星期几
算法步骤:
(1) 输入年份 year
(2) 根据公式:d=year+(year-1)/4-(year-100)/100+(yrar-1)/400 ; d=d%7; d=0 则表示为Sunday,d=1 表示Monday 计算这一年的元旦是星期几;
(3) 输入月份Month和日期day ,计算该日期是这个年份中的第几天(x).;
(4) 计算(x+d-1)%7 得到星期几;
程序:
// 根据输入的年月日计算该日期是星期几 (附加TODO 是否可以计算当天的阴历日期,阴历阳历日期转换?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入年月日(用逗号隔开如 1990,07,12):");
char[] sep = new char[] {' ',',',',' };
string[] tempstr;
while (true)
{
tempstr = Console.ReadLine().Split(sep, StringSplitOptions.RemoveEmptyEntries);
if (tempstr.Length != 3)
{
Console.Write("输入有误\n按任意键退出...");
Console.ReadKey();
Environment.Exit(0);
}
int year = Int32.Parse(tempstr[0]);
int month = Int32.Parse(tempstr[1]);
int day = Int32.Parse(tempstr[2]);
if (year > 0)
{
// 计算这一年的元旦(XXXX年1月1号)是星期几
int d = year + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
d = d % 7; // d=0 Sunday, d=1 Monday,
int sum=0,leap=0;
switch (month)
{
case 1: sum = 0; break;
case 2: sum = 31; break;
case 3: sum =59 ;break;
case 4: sum = 90; break;
case 5: sum = 120; break;
case 6: sum = 151; break;
case 7: sum = 181; break;
case 8: sum = 212; break;
case 9: sum = 242; break;
case 10: sum = 273; break;
case 11: sum = 303; break;
case 12: sum = 334; break;
default: Console.WriteLine("Error"); break;
}
sum += day;
// 判断是否为闰年:年份能被400整除或者年份能被4整除但不能被100整除的为闰年
if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0)
{
leap=1;
// Console.WriteLine("29"); // 闰年
}
else
{
leap = 0;
// Console.WriteLine("28"); // 平年
}
sum += leap;
int x = (sum + d - 1) % 7; // 计算这一天是星期几
switch (x)
{
case 0: Console.WriteLine("Sunday"); break;
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;
default: Console.WriteLine("Error"); break;
}
}
}
}
}
}