how to check for an integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Avery Mathews
    New Member
    • Feb 2012
    • 1

    how to check for an integer

    Hi I've just started c programming and I have a task which requires me to check if a certain value i calculated is an integer. I've tried using
    if (fmod(variable, 1)==0){
    integer..
    }else{
    not integer..

    but its not working for me..
    is there any other function that i can use?
    and I'm not sure what type of variable should I use(i.e int, double, float) to start with?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You appear to have been set an impossible task.

    You would need to start with a float or double. If you use an int then by definition the value you have is an integer. Here is the issue the float and double types are only approximations to any number, you can never count on them to be exact (particularly after calculations). Since you can convert a double to an integer by casting that means that the equality

    d - int(d) == 0

    where d is a double (or float) variable

    is never true. Even if you expect d to be an integer value it wont be it will be an approximation and d - int(d) will have a small positive or negative result.

    The best you can do is test to see if your double is close to an integer value

    Code:
    const double tolerance = 0.00001;
    if (((d - tolerance) < int(d)) && ((d + tolerance) > int(d))
    {
      // d is close to an integer
    }
    You can set the tolerance to get an answer to the accuracy you require and I also have an alarm bell going in my head that this algorithm may need to be more complex to deal with negative values of d.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      I'm not following you. You put the result of your calculation into a variable. So isn't the type of the variable determining the format of the result?

      If the variable is a float you cannot convert it to an int without drawing fire from the compiler about possible loss of data (integers have no decimal portion). A typecast just tells the compiler to shut up but the possible loss of data remains.

      If the variable is an int, then what it contains is an integer.

      Comment

      Working...