سؤال

I am working on a project for the Pebble platform. Apps are written in C, and my question is not specific to that platform.

The Pebble API has a Struct called PblTm that is populated every second by a line of code. My goal is to compare the struct with the current time. I have created PblTm structs and populated them with the times I need to compare against. I only care about the hour and minute sections of the structs. So far, I have the following code.

bool comp_time(int h1, int m1, int h2, int m2, int h3, int m3) {

    if((h1<=h2)  && (h2<=h3)) //Is start hour <= now hour <= end hour?
    {
        if((h1=h2) && (m2>=m1)) //If start hour = now hour, is now min >= start min ?
        {
            return true; 
        }
        if((h2=h3) && (m2<=m3)) //If end hour = now hour, if now min <= end min?
        {
            return true;
        }
        if((h1>h2) && (h2<h3)) //If start hour < now hour < end hour?
        {
            return true;
        }
    }
    else
    {
        return false;
    }
    return false;

}

I initially tried to feed the structs themselves as parameter to the function something like:

comp_time(&first_start,&now,&first_end);

And then referenced the elements of the struct inside the function, I could never get that to compile, and I couldn't find information on it. (I may have not have been searching for the correct terms).

I then changed to feeding the int parameters to the function itself like this:

comp_time(first_start.tm_hour,first_start.tm_min,now.tm_hour,now.tm_min,first_end.tm_hour,first_end.tm_min)

It is a quite clumsy way of doing it, but I have already done the work to type it all out. My main problem however, is that the comparison function doesn't function. It returns (apparently randomly, I have not been able to find a pattern) true for values that do not fit and false for some that fit.

Do you have any ideas?

هل كانت مفيدة؟

المحلول 2

Ok, so your parameter names make it very difficult to read the code and reason about it, so lets rewrite it a bit:

bool comp_time(int hstart, int mstart, int hnow, int mnow, int hend, int mend) {
  if (( hstart <= hnow ) && ( hnow <= hend ))
  {

So far so good. We know that if hnow is less than hstart or more than hend then it can't be true.

if((hstart==hnow) && (mnow>=mstart)) return true ;  // BAD

Besides the fix for == instead of =, this is still wrong. You're only testing one side of the boundary. You need to test against both start and end to make sure you're inside the range:

if ( ( (hstart < hnow ) || (mstart <= mnow ) ) &&
    ( (hnow < hend) || (mnow <= mend ) ) )  { return true ; }

نصائح أخرى

You should really update to Pebble SDK2 which provides a time_t value for time. This value is a timestamp (number of seconds since epoch) and you can easily compare it in one operation.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top