C编程-“ else if”是否不同于“ if”?

时间:2019-09-11 20:10:21

标签: c

这里是C程序,可以将天转换成年和月。我想问题出在第31行,如果是2月份的话,这是另外一个条件。

问题是,如果您输入天数为365,则不确定性为1天。输出为1年零1天。同样,如果输入的天数少于86 -88,则输入将变为无限。为什么?请给我一些认真的帮助。

#include<stdio.h>
int main () {

    int days, count = 0, week = 0, year = 0, month = 0, condition = 0, dayFweeks;
    float week_counter, year_counter;

    printf(" Input Days : ");
    scanf("%d", &days);

    dayFweeks = days;

    while (1) {
        if ( days == 0 )
            break;
        if ( count == 7) {
            week++;
            count = 0;
        }
        else if ( week == 4 && condition == 0 && month != 2) {
            month++;
            count += 3;
            days -= 3;
            week = 0;
            condition++;
        }
        else if ( week == 4 && condition == 1 && month != 2){
            month++;
            count += 2;
            days -= 2;
            week = 0;
            condition--;
        }
        else if ( week == 4 && month == 2) {
            month++;
            count += 1;
            days -= 1;
            week = 0;
            condition++;
        }
        else if ( month == 12) {
            year++;
            month = 0;
            week = 0;
        }
        days--;
        count++;
    }
    week_counter = dayFweeks / 7;
    if (dayFweeks == 0)
        printf(" 0 DAYS ARE NOT IN YEARS AND MONTHS");

    else
        printf("\n\n %d Year(s), %d Months and %d Day(s)\n Weeks : %.2f", year, month, count, week_counter);
}

1 个答案:

答案 0 :(得分:0)

由于您是根据随机的开始日期进行计算,因此似乎可以偷工减料。

首先,我要说的是每年365.25天,包括leap年。

然后,只需将您的天数除以该值即可得出年数。然后减去其余部分。

例如

500 days -> 500/365.25 = 1.36893 so 1 year
0.36893 * 12 months = 16.4271 so 16 months
0.4271 * 365.25/12 (average number of days per month) = 13 days

现在,计算年数,月数和天数应该非常容易