这几天在论坛看到很多马友,在讨论类的问题,写了一个用类实现输入年月日,判断这一天是这一年第几天的程序。- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace exam2
- {
- class Date
- {
- protected string year;
- protected string month;
- protected string day;
- protected string InitYear(string yy) //初始化年
- {
- this.year = yy;
- return this.year;
- }
- protected string InitMonth(string yy) //初始化月
- {
- this.month = yy;
- return this.month;
- }
- protected string InitDay(string yy) //初始化年
- {
- this.day = yy;
- return this.day;
- }
- protected bool IsRuiNian(string yy) //判断是不是闰年
- {
- int YY=int.Parse(yy);
- if (YY % 400 == 0 || (YY % 4 == 0 && YY % 100 == 0))
- return true;
- else
- return false;
- }
- protected int[,] GetMonth(string year) //获得月份的天数
- {
-
- int[,] Mounth = { {1,31},{2,28},{3,31},{4,30},{5,31},{6,30},{7,31},{8,31},{9,30},{10,31},{11,30},{12,31}};
- if (IsRuiNian(year))
- Mounth[1,1] = 29;
- return Mounth;
- }
- public int GetDays(string year, string month, string day)//计算总天数
- {
- int SumDay = int.Parse(day);//总天数
- int [,]Mounth = this.GetMonth(year);
- int mm = int.Parse(month);
- for (int i = 1; i < mm;i++ )//计算从1月到输入的月份的天数
- {
- SumDay += Mounth[i, 1];
- }
-
- return SumDay;
- }
- }
- class Program
- {
- //输入某年某月某日,判断这一天是这一年的第几天?
- static void Main(string[] args)
- {
- Date date=new Date();
- Console.Write("年:");
- string year = Console.ReadLine();
- Console.Write("月:");
- string month = Console.ReadLine();
- Console.Write("日:");
- string day = Console.ReadLine();
- Console.WriteLine(string.Format("{0}年{1}月{2}日是第{3}天:", year, month, day, date.GetDays(year, month, day)));//用Format格式化输出
- Console.ReadKey();
-
- }
- }
- }
复制代码 |
|