zero in c

This is a discussion on zero in c within the C Programming forums, part of the General Programming Boards category; I am implementing a while loop where a float variable changes value several times. I want the loop to stop ...

  1. #1
    Unregistered
    Guest

    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
    Posts
    14,826
    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.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    You can't compare floats for equality

    Try something like this
    Code:
    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

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