Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2509921
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-08-25 15:01:57

    定义一个结构体变量(包括年,月,日)。计算该日在本年中式第几天?注意闰年问题。
    我们需要顶一个一个关于日期的结构体,因为涉及到闰年问题,因此我们通过书写一个宏来判断是否为闰年的问题。我们可以把每个月的天数保存在一个数组中,然后根据输入的月份去判断去累加每一个月的天数。代码如下:

#include <stdio.h>
#define ISLOOP(year) (((year) % 4 == 0 && (year) % 100 != 0) || ((year) %400 == 0)) ? 1 : 0
struct date
{
       int year;
       int month;
       int day;
};
const int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int days(struct date *);
int main(int argc, char * argv[])
{
    struct date dt1,*p;
    p = &dt1;
    printf("please input year,month,day:");
    scanf("%d,%d,%d",&dt1.year,&dt1.month,&dt1.day);
    while (dt1.year < 1900 || dt1.month > 12 || dt1.month < 1 || dt1.day > 31 || dt1.day < 1)
    {
          printf("your put data is error,please reinput:\n");
          scanf("%d,%d,%d",&dt1.year,&dt1.month,&dt1.day);
    }
    printf("%d year %d month %d day is : %d day's.",p->year,p->month,p->day,days(p));
    system("pause");
    return 0;
}

int days(struct date *p)
{
    int *month = months;
    int i,result = 0;
    for (i = 0; i < p->month - 1;i++)
    {
        result +=*month++;
    }
    result += p->day;
    if(p->month > 2 && ISLOOP(p->year))
    {
        result += 1;
    }
    return result;
}


阅读(2534) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~