输入1-365 的一个数字判断它是几月几日
首先我们要想到怎么判断是一年的第几个月,然后判断是一个月的第几天;我们来看一看代码;
using System;
//第二个实验
namespace classes
{
enum MonthName
{
january,February,march,April,May,June,July,August,September,October,November,December
}
class Program
{ //B
static System.Collections.ICollection DaysInMonths=new int [12]{31,28,31,30,31,30,31,31,30,31,30,31}; //存储月份的天数
static void Main(string[] args){
try
{
Console.Write("输入1-365天的某一天\n");
string line =Console.ReadLine();
int dayNum=int.Parse(line);
if(dayNum<1||dayNum>365)
{
throw new ArgumentOutOfRangeException("输入是没有意义的!");
}
int monthNum=0;
foreach (int daysInMonth in DaysInMonths)
{
if(dayNum<=daysInMonth)
{
break;
}
else{
dayNum-=daysInMonth;
monthNum++;
}
}
MonthName temp=(MonthName)monthNum;
string monthName=Enum.Format(typeof(MonthName),temp,"g");
Console.WriteLine("{0} {1}",dayNum,monthName);
Console.Read();
}
catch(Exception caught)
{
Console.WriteLine(caught);
}
}
}
}
我们虽然完美解决了这个问题,但是我们要注意到的是,闰年有366天,这个只是一般情况,所以我们大胆挑战一下;
闰年的2月有29天,所以我们存储月份的数组要加入一个闰年的月份数组;
static System.Collections.ICollection DaysInMonths1=new int [12]{31,29,31,30,31,30,31,31,30,31,30,31};
代码如下:我们首先要输入年份判断是否是闰年;
using System;
//第二个实验
namespace classes
{
enum MonthName
{
january,February,march,April,May,June,July,August,September,October,November,December
}
class Program
{ //B
static System.Collections.ICollection DaysInMonths=new int [12]{31,28,31,30,31,30,31,31,30,31,30,31};
static System.Collections.ICollection DaysInMonths1=new int [12]{31,29,31,30,31,30,31,31,30,31,30,31};
static void Main(string[] args){
try
{
Console.Write("输入年份\n");
string year =Console.ReadLine();
int yearNum=int.Parse(year);
bool isLeapYear=(yearNum%4==0&&yearNum%100!=0||yearNum%400==0);
int maxDayNum = isLeapYear?366:365;//判断是不是闰年
if(isLeapYear==true)
{ //如果是闰年的话,把二月修改为29天
Console.Write("输入1-{0}天的某一天\n",maxDayNum);
string line1 =Console.ReadLine();
int dayNum1=int.Parse(line1);
if(dayNum1<1||dayNum1>maxDayNum)
{
throw new ArgumentOutOfRangeException("输入是没有意义的!");
}
int monthNum1=0;
foreach (int daysInMonth in DaysInMonths1)
{
if(dayNum1<=daysInMonth)
{
break;
}
else{
dayNum1-=daysInMonth;
monthNum1++;
}
}
MonthName temp1=(MonthName)monthNum1;
string monthName1=Enum.Format(typeof(MonthName),temp1,"g");
Console.WriteLine("{0} {1}",dayNum1,monthName1);
Console.Read();
}
Console.Write("输入1-{0}天的某一天\n",maxDayNum);
string line =Console.ReadLine();
int dayNum=int.Parse(line);
if(dayNum<1||dayNum>maxDayNum)
{
throw new ArgumentOutOfRangeException("输入是没有意义的!");
}
int monthNum=0;
foreach (int daysInMonth in DaysInMonths)
{
if(dayNum<=daysInMonth)
{
break;
}
else{
dayNum-=daysInMonth;
monthNum++;
}
}
MonthName temp=(MonthName)monthNum;
string monthName=Enum.Format(typeof(MonthName),temp,"g");
Console.WriteLine("{0} {1}",dayNum,monthName);
Console.Read();
}
catch(Exception caught)
{
Console.WriteLine(caught);
}
}
}
}
需要注意特殊天第60天,如果加入判断是否为闰年时,如果添加成功就显示时2月29日,如果失败就时3月1日。不能盲目输入天数,区别不开。