C语言程序100例之C#版-004
【程序4】
题目:输入某年某月某日,判断这一天是这一年的第几天?
1.程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊
情况,闰年且输入月份大于3时需考虑多加一天。
2.程序源代码:
C语言程序:
#include "stdio.h"
#include "conio.h"
main()
{
int day,month,year,sum,leap;
printf("/nplease input year,month,day/n");
scanf("%d,%d,%d",&year,&month,&day);
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=243;break;
case 10:sum=273;break;
case 11:sum=304;break;
case 12:sum=334;break;
default:printf("data error");break;
}
sum=sum+day; /*再加上某天的天数*/
if(year%400==0||(year%4==0&&year%100!=0)) /*判断是不是闰年*/
leap=1;
else
leap=0;
if(leap==1&&month>2) /*如果是闰年且月份大于2,总天数应该加一天*/
sum++;
printf("It is the %dth day.",sum);
getch();
}
##############################
C#程序1:
using System;
class DateOpinion
{
static void Main()
{
int x,y,z,a1=0;
Console.Write("请输入年份:");
x=Convert.ToUInt16(Console.ReadLine());
Console.Write("月份:");
y=Convert.ToUInt16(Console.ReadLine());
Console.Write("日期:");
z=Convert.ToUInt16(Console.ReadLine());
switch(y)
{
case 1:a1=0;break;
case 2:a1=31;break;
case 3:a1=59;break;
case 4:a1=90;break;
case 5:a1=120;break;
case 6:a1=151;break;
case 7:a1=181;break;
case 8:a1=212;break;
case 9:a1=243;break;
case 10:a1=273;break;
case 11:a1=304;break;
case 12:a1=334;break;
default:
Console.WriteLine("数据错误,请重新计算!");
break;
}
if(x%4==0||x%100==0)
a1=a1+1;
else
{
a1=a1+0;
}
a1=a1+z;
Console.WriteLine(a1);
}
}
##############################
C#程序2:
using System;
class DateOpinion
{
static void Main()
{
int x,y,z,a1=0,i;
Console.Write("请输入年份:");
x=Convert.ToUInt16(Console.ReadLine());
Console.Write("月份:");
y=Convert.ToUInt16(Console.ReadLine());
Console.Write("日期:");
z=Convert.ToUInt16(Console.ReadLine());
for(i=y-1;i>0;i--)
switch(i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
a1=a1+31;
break;
case 4:
case 6:
case 9:
case 11:
a1=a1+31;
break;
case 2:
if(x%4==0||x%100==0)
a1=a1+29;
else
a1=a1+28;
break;
default:
Console.WriteLine("数据错误,请重新计算!");
break;
}
a1=a1+z;
Console.WriteLine(a1);
}
}