Is there an “inverted” trunc function in C or C++? [duplicate]

亡梦爱人 提交于 2020-01-25 07:57:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!