简体   繁体   中英

what to use to check in between comparisons in c?

need to make ac program that will get the current time of pc and display if its traffic or not.

Traffic every : 7:00am - 10:00am && 17pm - 19pm

need help in time comparisons. im using if else.

if ((mytime > 7 && mytime < 10) && (mytime > 17 && mytime < 19))

Use || (OR) instead of && (AND). Or it will never work.

And to get the hour, do something like that:

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

int main() {
    time_t now = time(NULL);
    struct tm *now_tm = localtime(&now);
    int hour = now_tm->tm_hour;

    if ((hour > 7 && hour < 10) || (hour > 17 && hour < 19))
        printf("traffic\n");
    else
        printf("smooth\n");

    return 0;
}

You can even use seconds (source: http://www.cplusplus.com/reference/ctime/difftime/ ), like this:

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

int main ()
{
  time_t now;
  struct tm newyear;
  struct tm _7am;
  struct tm _10am;
  struct tm _5pm;
  struct tm _7pm;
  double mytime;
  double s_7am, s_10am, s_5pm, s_7pm;

  time(&now);

  newyear = *localtime(&now);
  newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
  newyear.tm_mon = 0;  newyear.tm_mday = 1;

  _7am = *localtime(&now);
  _7am.tm_hour = 7; _7am.tm_min = 0; _7am.tm_sec = 0;
  s_7am = difftime(mktime(&_7am),mktime(&newyear));

  _10am = *localtime(&now);
  _10am.tm_hour = 10; _10am.tm_min = 0; _10am.tm_sec = 0;
  s_10am = difftime(mktime(&_10am),mktime(&newyear));

  _5pm = *localtime(&now);
  _5pm.tm_hour = 17; _5pm.tm_min = 0; _5pm.tm_sec = 0;
  s_5pm = difftime(mktime(&_5pm),mktime(&newyear));

  _7pm = *localtime(&now);
  _7pm.tm_hour = 19; _7pm.tm_min = 0; _7pm.tm_sec = 0;
  s_7pm = difftime(mktime(&_7pm),mktime(&newyear));

  mytime = difftime(now,mktime(&newyear));

  if ((mytime > s_7am && mytime < s_10am) || (mytime > s_5pm && mytime < s_7pm)){
     printf("Traffic!");
  }else{
     printf("Smooth...");
  }


  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM