是否有“倒置"字样?在C或C ++中使用trunc函数? [英] Is there an "inverted" trunc function in C or C++?

查看:120
本文介绍了是否有“倒置"字样?在C或C ++中使用trunc函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C或C ++中是否有一个类似于trunc的函数,它可以对负数进行四舍五入并对正数进行四舍五入? 像本例一样:

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至-4或2.1至3

-3.3 to -4 or 2.1 to 3

我只能找到反"函数截断.但是很难相信这是不存在的.我真的必须首先通过if查询阳性,然后相应地对它进行四舍五入吗?我需要这个,因为我有两个向量之间的标量积的符号.所以1,-1或0.

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.

推荐答案

首先,您可以使用内联条件返回floorceil.在这里:

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);
}

另一种实现此功能的方法是截断数字,并将其绝对值增加一个.这也将起作用.不需要math.h但是,由于溢出,建议不要将其用于大量:

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

这篇关于是否有“倒置"字样?在C或C ++中使用trunc函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆