谁能看出这有什么问题(C 中与时间相关的函数)

标签 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'
  } 
}

最佳答案

如果将其编译为 C89 代码,则应在 block 的开头声明变量。您不能在 block 的中间声明 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); 
}

关于谁能看出这有什么问题(C 中与时间相关的函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1251288/

相关文章:

c++ - 尝试从 time_point (C++) 中减去 std::chrono::duration,但我的代码未编译。有什么建议么?

c - Rand 函数在 C 中无法正常工作

c - 什么是 "DNS_BLOCK_ASSERTIONS"(C 编译器标志)?

c - 如何从 MSI 数据库中提取部署文件

c - 为什么现在在 mingw 和 2017 中 printf ("%c"、 '\0' ) 存在差异?

javascript - JavaScript Date.now() 时间格式叫什么?

c++ - Bison 警告 : Empty rule for typed nonterminal

javascript - 以 12 小时格式显示预计到达时间 React Native

c - 使用 srand 插入随机数

C++ srand() 函数