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
Saspiron
source
to share
2 answers
As I said in the comments:
float signed_square(float x){
return x * fabs(x);
}
+11
druckermanly
source
to share
C99 supplies double copysign(double x, double y)
Functions
copysign
produce ax
signed and magnified valuey
.
float signed_square(float x) {
return copysignf(x*x, x);
}
+3
chux
source
to share