c#输入两个正整数:年份和月份,以空格分隔,输出这一年的这一月有多少天。需要考虑闰年。用switch
时间: 2024-09-22 16:06:33 浏览: 53
在C#中,你可以使用`switch`语句结合`DateTime`类来处理这个问题。首先,我们需要获取给定年份和月份对应的天数,同时考虑到闰年的情况。以下是一个示例代码:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("请输入年份(yyyy) 和 月份:mm:");
string input = Console.ReadLine(); // 获取用户输入
string[] numbers = input.Split(' '); // 分割字符串
int year = Int32.Parse(numbers[0]); // 年份
int month = Int32.Parse(numbers[1]); // 月份
int daysInMonth;
switch (month)
{
case 1:
daysInMonth = 31; break; // January always has 31 days
case 2:
if (IsLeapYear(year)) // 判断是否为闰年
daysInMonth = 29;
else
daysInMonth = 28;
break;
case 3:
daysInMonth = 31; break; // March has 31 days
case 4:
daysInMonth = 30; break; // April has 30 days
case 5:
daysInMonth = 31; break; // May has 31 days
case 6:
daysInMonth = 30; break; // June has 30 days
case 7:
daysInMonth = 31; break; // July has 31 days
case 8:
daysInMonth = 31; break; // August has 31 days
case 9:
daysInMonth = 30; break; // September has 30 days
case 10:
daysInMonth = 31; break; // October has 31 days
case 11:
daysInMonth = 30; break; // November has 30 days
case 12:
daysInMonth = 31; break; // December has 31 days
default:
throw new ArgumentException("Invalid month"); // 处理无效月份
}
Console.WriteLine($"{year}年{month}月有 {daysInMonth} 天。");
// 判断闰年的辅助函数
bool IsLeapYear(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
}
```
当你运行这个程序并输入年份和月份时,它会计算出指定月份的天数,并考虑闰年的情况。
阅读全文