Cycling variable, threshold

This is a discussion on Cycling variable, threshold within the C Programming forums, part of the General Programming Boards category; Hi there, I have a float called counter that goes from 0 to 31 and then back to 0. I ...

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    69

    Cycling variable, threshold

    Hi there,

    I have a float called counter that goes from 0 to 31 and then back to 0. I want to be able to specify a number x (0-31) and a threshold th, and check if the number is within th units from the counter.

    Sounds easy at first:
    if( abs(x - counter) <= th )

    But this doesn't work if x is close to 0 and counter is close to 31. I've thought about this for quite a while but can't seem to come up with a solution. Help would be greatly appreciated!

  2. #2
    Registered User ralu.'s Avatar
    Join Date
    Feb 2009
    Location
    Bucharest, RO
    Posts
    32
    First of all the abs function has this prototype:
    int abs(int j);
    It aspects an int not a float.

    Use one of this instead:

    #include <math.h>

    double fabs(double x);
    float fabsf(float x);
    I have stopped reading Stephen King novels. Now I just read C code instead.

  3. #3
    Registered User
    Join Date
    Dec 2006
    Posts
    69
    Thanks ralu, I'm using a language very similar to C but which has an abs function that is overloaded for many types.
    Code:
    Anyway, I found a solution:
       if(abs(a - (ctr % 32)) <= threshold)
          return true;
       else
          if(abs(32 + a - (ctr % 32)) <= threshold)
             return true;
          else
             return false;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 12:57 PM
  2. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  3. Use of variable
    By alice in forum C Programming
    Replies: 8
    Last Post: 06-05-2004, 07:32 AM
  4. Replies: 2
    Last Post: 04-12-2004, 01:37 AM
  5. write Variable and open Variable and get Information
    By cyberbjorn in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2004, 01:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21