Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Nov 2009
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Absolute value in java

    Hey, im trying to use absolute value in java so that way when i enter a negative distance, it doesn't add gas.
    Code:
    gas = gas - Distance/efficiency;
    im trying to make Distance an absolute value so if i add in a negative value, it doesn't add gas...

  • #2
    Regular Coder cs_student's Avatar
    Join Date
    Oct 2009
    Location
    ~/
    Posts
    195
    Thanks
    2
    Thanked 22 Times in 22 Posts
    Use the Math.abs() function.

    Code:
    gas -= Math.abs(distance) / efficiency;

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    And if the Math.abs() function didn't exist, you could easily code it thus:
    Code:
    gas -= ( distance < 0 ? - distance : distance ) / efficiency;
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    New Coder
    Join Date
    Nov 2009
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by cs_student View Post

    Code:
    gas -= Math.abs(distance) / efficiency;
    didn't work because it then let the gas get below 0, idk why,

    but
    Code:
    gas -= ( distance < 0 ? - distance : distance ) / efficiency;
    worked perfectly, it took out gas when i went backwards and never let me go below 0 in gas, its my fault tho, cs_student did exactly what i wanted it to do, make it an absolute variable, but what i wanted was just different than that, sorry

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Ummm...honest, Math.abs() is *IMPLEMENTED* in this way, essentially:

    Code:
    double abs( double v )
    {
         return ( v < 0 ? -v : v );
    }
    (With overloadings for all the numeric types, of course.)

    So... If my code "fixed" your problem, then you changed the problem between the time you tried Math.abs() and when you tried the ternary operator.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •