如何将日转换为年月周然后天

时间:2018-08-30 08:15:23

标签: c error-handling runtime-error programming-languages

在这里,我只用30天来计算月份,但我想像这样计算月份     这样的1月31日,2月28日或4月30日

我在逻辑上实现了这一目标。请帮我解决这个问题

#include<stdio.h>
void main()
{
int in_days, years, months, days, extra, week;
printf("Enter number of days : ");
scanf("%d", &in_days);
If(in_day>1460){
   years = in_days/365;
   extra = in_days%365;
   months = extra/30; 
   days = extra%30;
   printf("%d days is same as %d years + %d months + %d days", in_days, years, months, days);
} 
else If(in_day<1460 & & in_day>=365){
       years = in_days/365;
       extra = in_days%365;
       months = extra/30;
       days = extra%30;
       printf("%d days is same as %d years + %d months + %d days", in_days, years, months, days);
  } 
else If(in_day<365){
       months = in_day/30;
       days = in_day%30;
       printf("%d days is same as %d months + %d days", in_days, months, days);
  } 
else If(in_day<30){
       week= in_day/7;
       days = week%7;
       printf("%d days is same as %d months + %d days", in_days, week, days);
  } 
getch() ;
}

1 个答案:

答案 0 :(得分:0)

您可以添加函数来计算#months

#include<stdio.h>

int cal_months(int *days){
    int months_arr[] = {31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}, i, months = 1;
    if(*days < 31){
        return 0;
    }
    for(i = 1; i < 12; i++){
        if(*days < months_arr[i]){
            *days -= months_arr[i-1];
            break;
        }else{
            months ++;
        }
    }
    return months;
}

int main()
{
    int in_days, years, months, days, extra, week;
    printf("Enter number of days : ");
    scanf("%d", &in_days);
    if(in_days>1460){
        years = in_days/365;
        extra = in_days%365;
        months = cal_months(&extra);
        //days = extra%30;
        printf("%d days is same as %d years + %d months + %d days\n", in_days, years, months, extra);
    }else if(in_days<1460 && in_days>=365){
        years = in_days/365;
        extra = in_days%365;
        months = cal_months(&extra);
        //days = extra%30;
        printf("%d days is same as %d years + %d months + %d days\n", in_days, years, months, extra);
    }else if(in_days<365){
        days = in_days;
        months = cal_months(&days);
        printf("%d days is same as %d months + %d days\n", in_days, months, days);
    }else if(in_days<31){
        week= in_days/7;
        days = in_days%7;
        printf("%d days is same as %d weeks+ %d days\n", in_days, week, days);
    }
    return 0;
}

注意:该代码不能处理LEAP年。您应该添加自己的逻辑以包括此功能。