There is no standard library function that exactly matches what you said, but I will let you know how to do it instead.
(x > 0) - (x < 0)
//If you unscramble the code above,
if (x > 0) return 1;
if (x < 0) return -1;
return 0;
(x > 0) ? 1 : ((x < 0) ? -1 : 0)
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
//< If you don't want to see GCC issuing -Wtype-limits warning because of 0, write the following code together (select)
template <typename T> inline constexpr
int signum(T x, std::false_type is_signed) {
return T(0) < x;
}
template <typename T> inline constexpr
int signum(T x, std::true_type is_signed) {
return (T(0) < x) - (x < T(0));
}
template <typename T> inline constexpr
int signum(T x) {
return signum(x, std::is_signed<T>());
}
Function Circular)
C99:
C++11:
Usage)
#include <math.h> //C
#include <cmath> //C++11
...
float a = 1.0;
result1 = copysign(1.0, a); //1.0
result2 = copysign(10.0, a); //10.0
However, 0 of the floating point has a sign, so be careful when writing it
int main(){
float fl1 = (0.0);
float fl2 = (+0.0);
float fl3 = (-0.0);
cout << copysign(1.0, fl1) << endl; //1.0
cout << copysign(1.0, fl2) << endl; //1.0
cout << copysign(1.0, fl3) << endl; //-1.0
}
© 2024 OneMinuteCode. All rights reserved.