Home >Backend Development >C++ >Does C/C Have a Standard Sign Function for Floating-Point Numbers?
Is There a Standard Sign Function in C/C ?
Question:
I am seeking a function that outputs -1 for negative numbers and 1 for positive numbers. Despite its simplicity, I suspect this functionality may be available in a standard library somewhere. Specifically, I require a function that operates on float data types.
Answer:
Yes, there is a standard C function that serves this purpose, known as signum. However, it is important to note that this function is type-safe, meaning it can operate on various data types, not just floats. Here's a generic implementation of signum:
template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); }
This function offers several advantages over custom implementations:
Usage:
int sign = sgn(-1.5); // -1 sign = sgn(0.0); // 0 sign = sgn(3.14); // 1
Caveats:
In conclusion, the signum function provides a versatile and efficient solution for determining the sign of a number in C . While it may not be directly available for floats in the standard library, its type-safe implementation enables its use on a wide range of data types with remarkable accuracy.
The above is the detailed content of Does C/C Have a Standard Sign Function for Floating-Point Numbers?. For more information, please follow other related articles on the PHP Chinese website!