float to absolute value

This is a discussion on float to absolute value within the C Programming forums, part of the General Programming Boards category; Hi there I want to convert a float to its absolute value and I have discovered the fabs() function but ...

  1. #1
    jesse
    Guest

    Unhappy float to absolute value

    Hi there
    I want to convert a float to its absolute value and I have discovered the fabs() function but it only works if I set my variable to a double. I really want my variable to remain a float, is there a way to do this?
    Thanks

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    fabs() will work with floats, they'll just be promoted within the function.

    If you want to keep using floats (for whatever reason) then just make sure that the variable you are returning into is a float. Your compiler may warn you about possible loss of data but you can either ignore these warnings or cast the function to a float -

    float y = (float)fabs(x);

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    if ( x < 0.0 ) x = -x;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    jesse
    Guest

    Smile

    Thanks Zen and Salem!
    Excellent help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-13-2009, 04:25 PM
  2. Replies: 14
    Last Post: 06-28-2006, 02:58 AM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 12:58 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM

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