我的日期代码有问题吗?

时间:2012-03-24 06:51:56

标签: c

描述:给定START_GREGORIAN_CALENDAR之后的日期,此函数返回下一个星期四之前的天数。例如,2011年3月16日(2011,3,16),该函数将返回1,而2011年3月17日(2011,3,17),函数将返回7。

int daysToNextThursday (int year, int month, int day) {
    int Thursday;
    Thursday = 7;
    return (Thursday - day);   
}

代码编译正确,但是当我输入日期时,例如2011年3月3日,我没有得到正确的答案。 请注意,这是我编写的大量代码的一部分,它完美无缺。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

是的,我有个主意。我的想法是你回去重新考虑你选择的算法,以确定一天是星期四。这是错误的: - )

现在,就像一个每天两次正确的破碎时钟一样,你可能会发现输入参数可以给你正确答案,但它们将是例外而不是规则。

如果您想知道下周四何时是从给定日期开始,C就会为此提供日期和时间函数:

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

static char *textday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

int main (int argc, char *argv[]) {
    int year, month, day, today, thursday;
    struct tm *mytm;
    time_t mytime;

    // Get all arguments (minimal error checks).

    if (argc != 3) {
        printf ("Usage: next_thursday <year> <month>\n");
        return -1;
    }
    year = atoi (argv[1]);
    month = atoi (argv[2]);

    // Do first fourteen days of the month.

    for (day = 1; day <= 14; day++) {

直到那里,它只是获取参数并开始循环。计算的内容如下,设置一个有用的struct tm然后强制我们的年,月和日。然后mktime会为我们填写tm_wday(星期几)字段,我们可以用它来计算到星期四的天数。

        // Make the tm structure based on date (and midday).

        mytime = time (0);
        mytm = localtime (&mytime);
        mytm->tm_year = year - 1900;
        mytm->tm_mon = month - 1;
        mytm->tm_mday = day;
        mytm->tm_hour = 12;
        mytime = mktime (mytm);

        // Output filled in fields and days till next Thursday.

        today = mytm->tm_wday;
        thursday = (11 - today) % 7;
        if (thursday == 0)
            thursday = 7;
        printf ("%04d-%02d-%02d, weekday = %d (%s), days till Thu = %d\n",
            mytm->tm_year + 1900, mytm->tm_mon + 1, mytm->tm_mday,
            today, textday[today], thursday);
    }

    return 0;
}

请注意,thursday计算有点模数 - 它只是用来根据下表给出我们的天数:

 today   thursday
-------  --------
0 (sun)      4
1 (mon)      3
2 (tue)      2
3 (wed)      1
4 (thu)      7
5 (fri)      6
6 (sat)      5

如果您想要更易读的解决方案,可以使用:

if (today < 4) thursday = 4 - today;
else           thursday = 11 - today;

此程序为2011-03输出以下内容:

2011-03-01, weekday = 2 (Tue), days till Thu = 2
2011-03-02, weekday = 3 (Wed), days till Thu = 1
2011-03-03, weekday = 4 (Thu), days till Thu = 7
2011-03-04, weekday = 5 (Fri), days till Thu = 6
2011-03-05, weekday = 6 (Sat), days till Thu = 5
2011-03-06, weekday = 0 (Sun), days till Thu = 4
2011-03-07, weekday = 1 (Mon), days till Thu = 3
2011-03-08, weekday = 2 (Tue), days till Thu = 2
2011-03-09, weekday = 3 (Wed), days till Thu = 1
2011-03-10, weekday = 4 (Thu), days till Thu = 7
2011-03-11, weekday = 5 (Fri), days till Thu = 6
2011-03-12, weekday = 6 (Sat), days till Thu = 5
2011-03-13, weekday = 0 (Sun), days till Thu = 4
2011-03-14, weekday = 1 (Mon), days till Thu = 3