C程序我想知道是否还有简化我的dayofyear计划?

时间:2014-04-18 18:19:36

标签: c unix

我是C的新手,我编写了这个C程序,让用户输入一年中的某一天,作为回报,程序将输出月份和月份的哪一天。程序运行正常,但我想现在简化程序。我理解我需要一个循环,但我不知道如何去做。这是程序

#include <stdio.h>

void SplitDate(int dayofyear, int year, int *month, int *day);

int main() {
int month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int year, dayofyear, *day;

printf("Enter the day of the year: ");
scanf("%d", &dayofyear);
printf("Enter the year: ");
scanf("%d", &year);
printf("Day %d of year %d falls on:\n ",dayofyear, year);

SplitDate(dayofyear, year, month, day);

}

void SplitDate(int dayofyear, int year, int *month, int *day)
{
if(dayofyear >=1 && dayofyear <= 31)
    {
      printf("month = 1    day = %d\n",dayofyear);
    }
  else if(dayofyear >=32 && dayofyear <= 59)
    {
      printf("month = 2   day = %d\n", dayofyear - 31);
    }
  else if(dayofyear >=60 && dayofyear <=90)
    {
      printf("month = 3  day = %d\n", dayofyear - 59);
    }
  else if(dayofyear >=91 && dayofyear <=120)
   {
     printf("month = 4   day = %d\n", dayofyear - 90);
   }
  else if(dayofyear >=121 && dayofyear <=151)
   {
     printf("month = 5   day = %d\n", dayofyear - 120);
   }
  else if(dayofyear >=151 && dayofyear <=180)
   {
     printf("month = 6   day = %d\n", dayofyear - 150);
   }
  else if(dayofyear >=181 && dayofyear <=211)
   {
     printf("month = 7   day = %d\n", dayofyear - 180);
   }
  else if(dayofyear >=212 && dayofyear <=242)
   {
     printf("month = 8   day = %d\n", dayofyear - 211);
   }
  else if(dayofyear >=243 && dayofyear <=272)
   {
     printf("month = 9   day = %d\n", dayofyear - 242);
   }
  else if(dayofyear >=273 && dayofyear <=303)
   {
     printf("month = 10    day = %d\n", dayofyear -272 );
   }
  else if(dayofyear >=304 && dayofyear <=333)
   {
     printf("month = 11   day = %d\n", dayofyear - 303);
   }
  else if(dayofyear >=334 && dayofyear <=364)
   {
     printf("month = 12   day = %d\n", dayofyear - 333);
   }
}

2 个答案:

答案 0 :(得分:0)

阅读C标准库<time.h>标题,尤其是ctime()asctime()。了解如何使用它们。

答案 1 :(得分:0)

void SplitDate(int dayofyear, int year, int *month, int *day){
    static int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    //months[2] : Requires a correction of leap year
    int i;
    for(i=1;i<=12;++i){
        if(dayofyear > months[i]){
            dayofyear -= months[i];
        } else {
            printf("month = %d\t day = %d\n", i, dayofyear);
            break;
        }
    }
}