问题
Is there a function in C or C ++ - similar to trunc - that rounds off negative numbers and rounds up positive numbers? Like in this example:
-3.3 to -4 or 2.1 to 3
I could only find the "inverse" function trunc. But can hardly believe that this does not exist. Do I really have to first query the positivity via if and then round it up accordingly? I need this because I have the sign of the scalar product between two vectors. So either 1, -1 or 0.
回答1:
First, you can use an inline conditional to either return the floor
or the ceil
. Here:
#include <math.h>
inline double InvertedTrunc(double Number) {
return Number < 0 ? floor(Number) : ceil(Number);
}
Another approach to achieve this functionality is just truncating the number, and increasing its absolute value by one. This will also work. Does not require math.h
However, it is not recommended for large numbers because of overflow:
inline double InvertedTrunc(double Number) {
return (Number == (int)Number ? Number : ((int)Number)+(Number < 0 ? -1 : 1)); //casting to int truncates it
} //However, this option is susceptible to overflow, and it is not recommended for large numbers
来源:https://stackoverflow.com/questions/59899540/is-there-an-inverted-trunc-function-in-c-or-c