【问题标题】:Can anyone see what is wrong with this (time related functions in C)谁能看到这有什么问题(C中与时间相关的函数)
【发布时间】:2009-08-09 12:20:59
【问题描述】:
#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'
  } 
}

【问题讨论】:

  • @Matthew:很可能,尤其是因为它在 GCC 下编译得很好。
  • @Zed:是的,这是一个隐含的unsigned int。例如,这有点像如何将long int 声明为long
  • @htw,添加 --std=c90 -pedantic-errors 你也会遇到 gcc 错误。

标签: c time srand


【解决方案1】:

如果将其编译为 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); 
}

【讨论】:

    【解决方案2】:

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

    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 要求在函数开头定义变量,这会导致代码失败。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:
        ISO C90 forbids mixed declarations and code
        

        【讨论】:

          猜你喜欢
          • 2018-05-31
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 2017-12-11
          • 2021-07-14
          • 1970-01-01
          • 2018-10-25
          • 2020-11-30
          相关资源
          最近更新 更多