任何人都可以看到这有什么问题(C中的时间相关功能)

时间:2009-08-09 12:20:59

标签: c time srand

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

static struct tm createDate(unsigned day, unsigned mon, int year) {
       struct tm b = {0,0,0,day,mon-1,year-1900}; return b; 
}

static int dateExceeded(unsigned day, unsigned mon, int year) {
    struct tm b = createDate(day,mon,year); 
    time_t y = mktime(&b), now; 
    time(&now);  // error C2143: syntax error : missing ';' before 'type'
    double diff = difftime(y, now) / (60 * 60 * 24);  // error C2065: 'diff' : undeclared identifier
    return (diff < 0); 
}

static void randomEvent(){
    srand(time(NULL));
    if ( rand()%10) {
            printf("Do something here\n"); // C2143: syntax error : missing ';' before 'type'
  } 
}

4 个答案:

答案 0 :(得分:5)

如果要将其编译为C89代码,则应在块的开头声明变量。您不能在块的中间声明double diff

static int dateExceeded(unsigned day, unsigned mon, int year) {
    double diff;
    struct tm b = createDate(day,mon,year); 
    time_t y = mktime(&b), now; 
    time(&now); 
    diff = difftime(y, now) / (60 * 60 * 24);
    return (diff < 0); 
}

答案 1 :(得分:0)

嗯,我似乎无法重现这一点。使用您的确切代码:

1>------ Build started: Project: so_1251288, Configuration: Debug Win32 ------
1>Compiling...
1>so_1251288.cpp
1>c:\users\matthew iselin\documents\visual studio 2008\projects\so_1251288\so_1251288\so_1251288.cpp(21) : warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>Linking...
1>Build log was saved at *snip*
1>so_1251288 - 0 error(s), 1 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

我以为你使用的是Visual C ++。你用的是什么版本?您的环境配置为什么?

我唯一能想到的是你可能无意中启用了Unicode而不是多字节字符编码......但这不应该导致你看到的错误。

编辑:我甚至无法通过创建Visual C ++ CLR应用程序并直接粘贴代码来重现。我们需要更多信息来诊断问题。

编辑2:实际上,当我编译为C(/ TC)而不是C ++(/ TP)代码时,我可以重现。正如已经提到的,C89要求在函数开头定义变量,这会导致代码失败。

答案 2 :(得分:0)

代码中也有错误。你应该在程序的生命周期中只调用一次srand。如果你每次在rand()之前调用srand,可能会一次又一次地获得相同的值。

答案 3 :(得分:0)

ISO C90 forbids mixed declarations and code