English 中文(简体)
两个日期之间的方案天数
原标题:C program days between two dates
  • 时间:2012-04-25 03:48:48
  •  标签:
  • c

我写了一个节目should在两个日期之间找到日子,但有一些动.。 在我宣读时,这一逻辑在我头上是完美的,因此,我假定我有某种yn错,我会把这种错误 over倒在一边。

首先,在不同年份进入两个日期时,产出总是在大约一个月之内(多数情况下为31个,但有一个情况下为32个)。 第二,两个日期完全是一个月,将第二个月的天数(即1/1/1至2/1/1的天数为28天)。 这一方案不可避免地还有其他一些令人厌恶的事情,但我希望,这种信息足以帮助你掩盖我做错的事情。 就我的生活而言,我可以自行表明这一点。 我对C来说是比较新的,因此请说是根le=

成就

// Calculates the number of calendar days between any two dates in history (beginning with 1/1/1).

#include <stdio.h>
#include <stdlib.h>

void leap(int year1, int year2, int *leap1, int *leap2);
void date(int *month1, int *day1, int *year1, int *month2, int *day2, int *year2, int *leap1, int *leap2);

int main(void)
{
        int month1, day1, year1, month2, day2, year2, leap1, leap2;
        int daysPerMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
        int daysPerMonthLeap[] = {31,29,31,30,31,30,31,31,30,31,30,31};

        leap(year1, year2, &leap1, &leap2);
        date(&month1, &day1, &year1, &month2, &day2, &year2, &leap1, &leap2);

        if(year1 == year2)
        {
                int i, total;

                if(month1 == month2)                            // Total days if month1 == month2
                {
                        total = day2 - day1;
                        printf("There are %d days between the two dates.", total);
                }
                else
                {
                    if(leap1 == 1)
                        total = daysPerMonthLeap[month1] - day1;
                    else
                        total = daysPerMonth[month1] - day1;

                    for(i = month1 + 1; i < month2; i++)        // Days remaining between dates (excluding last month)
                    {
                        if(leap1 == 1)
                            total += daysPerMonthLeap[i];
                        else
                            total += daysPerMonth[i];
                    }

                    total += day2;                              // Final sum of days between dates (including last month)

                    printf("There are %d days between the two dates.", total);
                }
        }
        else                                                    // If year1 != year2 ...
        {
                int i, total, century1 = ((year1 / 100) + 1) * 100, falseleap = 0;

                if(leap1 == 1)
                    total = daysPerMonthLeap[month1] - day1;
                else
                    total = daysPerMonth[month1] - day1;

                for(i = month1 + 1; i <= 12; i++)               // Day remaining in first year
                {
                    if(leap1 == 1)
                        total += daysPerMonthLeap[i];
                    else
                        total += daysPerMonth[i];
                }

                for(i = 1; i < month2; i++)                     // Days remaining in final year (excluding last month)
                {
                    if(leap2 == 1)
                        total += daysPerMonthLeap[i];
                    else
                        total += daysPerMonth[i];
                }

                int leapcount1 = year1 / 4;                     // Leap years prior to and including first year
                int leapcount2 = year2 / 4;                     // Leap years prior to and NOT including final year
                if(year2 % 4 == 0)
                        leapcount2 -= 1;

                int leaptotal = leapcount2 - leapcount1;        // Leap years between dates

                for(i = century1; i < year2; i += 100)          // "False" leap years (divisible by 100 but not 400)
                {
                        if((i % 400) != 0)
                                falseleap += 1;
                }

                total += 365 * (year2 - year1 - 1) + day2 + leaptotal - falseleap;      // Final calculation
                printf("There are %d days between the two dates.", total);
        }
        return 0;
}

void leap(int year1, int year2, int *leap1, int *leap2)             // Determines if first and final years are leap years
{
        if(year1 % 4 == 0)
        {
                if(year1 % 100 == 0)
                {
                        if(year1 % 400 == 0)
                                *leap1 = 1;
                        else
                                *leap1 = 0;
                }
                else
                        *leap1 = 1;
        }
        else
                *leap1 = 0;

        if(year2 % 4 == 0)
        {
                if(year2 % 100 == 0)
                {
                        if(year2 % 400 == 0)
                                *leap2 = 1;
                        else
                                *leap2 = 0;
                                }
                else
                        *leap2 = 1;
        }
        else
                *leap2 = 0;
}

void date(int *month1, int *day1, int *year1, int *month2, int *day2, int *year2, int *leap1, int *leap2)
{
        for(;;)                     // Infinite loop (exited upon valid input)
        {
                int fail = 0;
                printf("
Enter first date: ");
                scanf("%d/%d/%d", month1, day1, year1);
                if(*month1 < 1 || *month1 > 12)
                {
                        printf("Invalid entry for month.
");
                        fail += 1;
                }
                if(*day1 < 1 || *day1 > 31)
                {
                        printf("Invalid entry for day.
");
                        fail += 1;
                }
                if(*year1 < 1)
                {
                        printf("Invalid entry for year.
");
                        fail += 1;
                }
                if(daysPerMonth[month1] == 30 && *day1 > 30)
                {
                        printf("Invalid month and day combination.
");
                        fail += 1;
                }
                if(*month1 == 2)
                {
                        if(*leap1 == 1 && *day1 > 29)
                        {
                            printf("Invalid month and day combination.
");
                            fail += 1;
                        }
                        else if(*day1 > 28)
                        {
                            printf("Invalid month and day combination.
");
                            fail += 1;
                        }
                }
                if(fail > 0)
                        continue;
                else
                        break;
        }

        for(;;)
        {
                int fail = 0;
                printf("
Enter second date: ");
                scanf("%d/%d/%d", month2, day2, year2);
                if(*year1 == *year2)
                {
                        if(*month1 > *month2)
                        {
                                printf("Invalid entry.
");
                                fail += 1;
                        }
                        if(*month1 == *month2 && *day1 > *day2)
                        {
                                printf("Invalid entry.
");
                                fail += 1;
                        }
                }
                if(*month2 < 1 || *month2 > 12)
                {
                        printf("Invalid entry for month.
");
                        fail += 1;
                }
                if(*day2 < 1 || *day2 > 31)
                {
                        printf("Invalid entry for day.
");
                        fail += 1;
                }
                if(*year2 < 1)
                {
                        printf("Invalid entry for year.
");
                        fail += 1;
                }
                if(daysPerMonth[month2] == 30 && *day2 > 30)
                {
                        printf("Invalid month and day combination.
");
                        fail += 1;
                }
                if(*month2 == 2)
                {
                        if(*leap2 == 1 && *day2 > 29)
                        {
                            printf("Invalid month and day combination.
");
                            fail += 1;
                        }
                        else if(*day2 > 28)
                        {
                            printf("Invalid month and day combination.
");
                            fail += 1;
                        }
                }
                if(fail > 0)
                        continue;
                else
                        break;
        }
}
问题回答

首先,leap>/code>功能过于复杂;你不需要在一项职能呼吁中完成这两个日期,我相信,可以更简明扼要地写出,以便更加明显正确。 这里的版本I ve got 环绕该版succinct,但我相信,很容易检查逻辑:

int is_leap_year(int year) {
        if (year % 400 == 0) {
                return 1;
        } else if (year % 100 == 0) {
                return 0;
        } else if (year % 4 == 0) {
                return 1;
        } else {
                return 0;
        }
}

You could call it like this:

int year1, year2, leap1, leap2;
year1 = get_input();
year2 = get_input();
leap1 = is_leap_year(year1);
leap2 = is_leap_year(year2);

没有点人,法典的重复大大减少。 是的,我知道,is_leap_year(>可减为单一if(......)说明,但我很容易读。

第二,我认为你在0个指数阵列和1个指数化人类月之间再次出现不匹配的情况:

            if(*month1 < 1 || *month1 > 12)

v

    int daysPerMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};

第三,我认为,每月天数可以略微计算:

int days_in_month(int month, int year) {
        int leap = is_leap_year(year);
        /*               J   F   M   A   M   J   J   A   S   O   N   D */
        int days[2][12] = {{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
                           {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
        if (month < 0 || month > 11 || year < 1753)
                return -1;

        return days[leap][month];
}

在此,我假定1月份为零;你需要迫使法典其余部分相应。 (我从()。 采用类似惯例的最佳部分是,从差额计算中取消租赁条件。

第四,你将外围阵列重新编号为:

            for(i = month1 + 1; i <= 12; i++)
            {
                if(leap1 == 1)
                    total += daysPerMonthLeap[i];

这只是零指数阵列和1个指数月问题的另一个例子——但确保你在你确定月份时也确定this

我担心的是,我尚未发现所有问题——你可能会发现在投入之后的第一和第二天,即sort,删除所有这些验证代码——然后在之前使用<代码>,并在之后使用<>,或者在“之后”提供易于在计算核心中思考的名字。

这不是一个完整的答案。 我只想提及计算出跳跃年份的更好办法(从<条码>提取)。 《方案规划语言——第41页)

if ((year % 4 == 0 && year % 100 != 0) || year % 400 ==0)
    printf("%d is a leap year 
", year);
else
    printf("%d is not a leap year 
", year);

将每月指数降低1。

What I mean to say is January will correspond to daysPerMonth[0] or daysPerMonthLeap[0] and not daysPerMonth[1] or daysPerMonthLeap[1]. The reason for this being array indexes start from 0.

So, wherever you are using month1, month2 insidedaysPerMonth[] or daysPerMonthLeap[], use month1-1 and month2-1 instead.

I hope this is clear enough. Otherwise, feel free to comment.

变化

int daysPerMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int daysPerMonthLeap[] = {31,29,31,30,31,30,31,31,30,31,30,31};

页: 1

int daysPerMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int daysPerMonthLeap[] = {0,31,29,31,30,31,30,31,31,30,31,30,31};

i.e. pad the arrays at the beginning since all the code relies on the array values 页: 1 start at element 1 rather than element 0.

这将消除你所抱怨的错误。

The other problem is an off-by-one error when you add day2 页: 1 the 页: 1tal. In both cases you should add day2 - 1 rather than day2. This is also due 页: 1 the date indexes starting at 1 instead of 0.

After I made these changes (plus a couple just 页: 1 get the code 页: 1 compile), it works properly.

There are multiple problems in your code snippet.. but I must say it is a very good attempt. There are many short cuts to what you re try to achieve.

我撰写了以下方案,确定了两个日期之间的天数。 您可将此作为参考。

#include <stdio.h>
#include <stdlib.h>

char *month[13] = {"None", "Jan", "Feb", "Mar", 
                   "Apr", "May", "June", "July", 
                   "Aug", "Sept", "Oct", 
                   "Nov", "Dec"};

/*
daysPerMonth[0] = non leap year
daysPerMonth[1] = leap year
*/
int daysPerMonth[2][13] = {{-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
                           {-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};

typedef struct _d {
    int day;        /* 1 to 31 */
    int month;      /* 1 to 12 */
    int year;       /* any */
}dt;

void print_dt(dt d)
{
    printf("%d %s %d 
", d.day, month[d.month], d.year);
    return;
}

int leap(int year)
{
    return ((year % 4 == 0 && year % 100 != 0) || year % 400 ==0) ? 1 : 0;
}

int minus(dt d1, dt d2)
{
    int d1_l = leap(d1.year), d2_l = leap(d2.year);
    int y, m;
    int total_days = 0;

    for (y = d1.year; y >= d2.year ; y--) {
        if (y == d1.year) {
            for (m = d1.month ; m >= 1 ; m--) {
                if (m == d1.month)  total_days += d1.day;
                else                total_days += daysPerMonth[leap(y)][m];
                // printf("%d - %5s - %d - %d 
", y, month[m], daysPerMonth[leap(y)][m], total_days);
            }
        } else if (y == d2.year) {
            for (m = 12 ; m >= d2.month ; m--) {
                if (m == d2.month)  total_days += daysPerMonth[leap(y)][m] - d2.day;
                else                total_days += daysPerMonth[leap(y)][m];
                // printf("%d - %5s - %d - %d 
", y, month[m], daysPerMonth[leap(y)][m], total_days);
            }
        } else {
            for (m = 12 ; m >= 1 ; m--) {
                total_days += daysPerMonth[leap(y)][m];
                // printf("%d - %5s - %d - %d 
", y, month[m], daysPerMonth[leap(y)][m], total_days);
            }
        }

    }

    return total_days;
}

int main(void)
{
    /* 28 Oct 2018 */
    dt d2 = {28, 10, 2018};

    /* 30 June 2006 */
    dt d1 = {30, 6, 2006};

    int days; 

    int d1_pt = 0, d2_pt = 0;

    if (d1.year  > d2.year)     d1_pt += 100;
    else                        d2_pt += 100;
    if (d1.month > d2.month)    d1_pt += 10;
    else                        d2_pt += 10;
    if (d1.day   > d2.day)      d1_pt += 1;
    else                        d2_pt += 1;

    days = (d1_pt > d2_pt) ? minus(d1, d2) : minus(d2, d1);

    print_dt(d1);
    print_dt(d2);
    printf("number of days: %d 
", days);

    return 0;
}

产出如下:

$ gcc dates.c 
$ ./a.out 
30 June 2006 
28 Oct 2018 
number of days: 4503 
$ 

注:这不是一个完整的方案。 它缺乏投入验证。

希望!

//Difference/Duration between two dates
//No need to calculate leap year offset or anything
// Author: Vinay Kaple
# include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
    int days_add, days_sub, c_date, c_month, b_date, b_month, c_year, b_year;
    cout<<"Current Date(dd mm yyyy): ";
    cin>>c_date>>c_month>>c_year;
    cout<<"Birth Date(dd mm yyyy): ";
    cin>>b_date>>b_month>>b_year;
    int offset_month[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
    days_add = c_date + offset_month[c_month-1];
    days_sub = b_date + offset_month[b_month-1];
    int total_days = (c_year-b_year)*365.2422 + days_add - days_sub+1;
    cout<<"Total days: "<<total_days<<"
";
    int total_seconds = total_days*24*60*60;
    cout<<"Total seconds: "<<total_seconds<<"
";
    return 0;
}




相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签