Thread: zero in c

  1. #1

    zero in c

    I am implementing a while loop where a float variable changes value several times. I want the loop to stop when the value of the variable reaches 0. I included this line in my code:
    while ( (f(c)!=0) && (ABS((b-a)/b)>=0.000005) )
    It complies, but when it executes it keeps going longer than it should (i.e. it terminates when the 2nd condition is false. it should terminate before that--when the 1st condition becomes false).

    Is there anyway that I can change my while statement to make my program run better.
    I've tried using "f(c)!=0.00000" since the variable is a float, but this doesn't work either.

    Please help.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Floats suck for comparisons. Typecast it to an integer, except you'll lose your precision, or better yet, sprintf() it to a buffer, then check each character to see if they're '0' or '.' ... any other character means it's not the value you want.

    Hope is the first step on the road to disappointment.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    You can't compare floats for equality

    Try something like this
    do {
       // some calcs
    } while ( fabs((b-a)/b) > 0.00001 );
    This should terminate the loop when the answer is 'close enough'. It's up to you to define what close enough is.

    But bear in mind that floats have only 6 digits of precision, which means you can't compare very large numbers with very small numbers effectively.

Popular pages Recent additions subscribe to a feed