c#,设计控制台应用程序,输出2023年的日历,每一周为一行。
输出如下:
3条回答 默认 最新
- 「已注销」 2023-03-10 12:41关注
根据你给出的图显示,加入输入验证,实现如下,望采纳谢谢:
internal class Program { public static void Main(string[] args) { Console.Write("请输入年份:"); //输入验证 int iYear; String strResult = Console.ReadLine(); while (!Int32.TryParse(strResult, out iYear)) { Console.WriteLine("请输入正确的年份!"); Console.Write("\n"); Console.Write("请输入年份:"); strResult = Console.ReadLine(); } bool bEstimate = LeapYear(iYear); // 判断是否闰年 PrintDateOfYear(bEstimate, iYear); // 打印日期 Console.ReadLine(); } // 打印日历表 private static void PrintDateOfYear(bool bEstimate,int iYear) { for (int month = 1; month <= 12; month++) { int j; int day = DayOfMonth(bEstimate, month);//判断月份的天数 int blank = GetWeekByDay(iYear, month, 1);//计算空格 Console.WriteLine(string.Format("{0}年{1}月", iYear, month)); Console.Write(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\n", "周日","周一","周二","周三","周四","周五","周六")); for (j = 1; j <= blank; j++)//添加空格 { Console.Write("\t"); } for (int i = 1; i <= day; i++) { int a = 8 - j; if ((i + 7 - a) % 7 == 0 || i == day) { Console.Write(i + "\n"); } else { Console.Write(i + "\t"); } } Console.Write("\n"); } } private static int DayOfMonth(bool Estimate, int month)//判断指定月份的天数 { int day; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 4: case 6: case 9: case 11: day = 30; break; case 2: if (Estimate) day = 29; else day = 28; break; default: day = 0; break; } return day; } // 判断是否为闰年 private static bool LeapYear(int year) { if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) return true; return false; } // 根据年月日计算星期数 private static int GetWeekByDay(int year, int month, int day) { return (int)new DateTime(year, month, day).DayOfWeek; } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用