Square number, but keep the sign (in s)

Is there an easy way to keep the sign after squaring the value. I currently have:

float signed_square(float x) {
    if (x > 0) {
        return x * x;
    } else {
        return -(x * x);
    }
}

      

+3


source to share


2 answers


As I said in the comments:



float signed_square(float x){
    return x * fabs(x);
}

      

+11


source


C99 supplies double copysign(double x, double y)

Functions copysign

produce a x

signed and magnified value y

.



float signed_square(float x) {
  return copysignf(x*x, x);
}

      

+3


source







All Articles