tags:

views:

153

answers:

5

How can I change the sign of a number?

abs(); will not return me a negative when the input is positive, correct? I need the opposite sign.

+1  A: 

Check out Math.Abs (answer to previous version of question).

Use the negative sign:

var answer = -amount;
Stephen Cleary
A: 

in C++, simply abs(x) which is in math.h
This is the Absolute Value function.

shoosh
Actually, `abs` is defined in `<cstdlib>` and is overloaded for `int` and `double`. In `<cmath>` you'll find `fabs`, which is overloaded for `float`, `double`, and `long double`.
GMan
+8  A: 

Just multiply by -1:

double d = 1.2345;
double opposite = d * -1;
Joel Coehoorn
wow @ how the simplest answer solvesi was bulding string parsers to add or remove the -
Smoka
Why not `opposite = -d;`?
GMan
+9  A: 

Dude. Minus.

double d = 1.1234;
double opposite = -d;
calmh
+1  A: 

This is too obvious:

n = -n

You should use:

n = ~--n;

..or, if you like the OR bitwise, use:

 n = (0xffffffff ^ n) + 1;

...if that +1 is too obvious for you, this is a sure bet:

n ^= 0xffffffff;
int m;
for (m = 1; m != 0 && ((n & m) != 0); m <<= 1);
n |= m;
if (m == 0) n = m;
else for (m >>= 1; m != 0; n ^= m, m >>=1);

...there's also the option for people who want to make sure none of their processing power goes unused:

public int invert(int n) {
  Random r = new Random();
  while (true) {
    int s = r.nextInt();
    if ((s + n) == 0) {
      return s;
    }
  }
}
Jon Bringhurst
+1 for advanced mathematics.
bowenl2