简体   繁体   English

C++ RoundUp 就像在 Excel 那个楼层的负数和正数上的 ceil

[英]C++ RoundUp like in Excel that floor's negative numbers and ceil's on positive numbers

Excel has a function called ROUNDUP, which not being a mathematician I would call a true round up or at least more logical to me, in that it makes makes a positive value like 0.5 value into 1 and a negative value like -0.5 into -1. Excel 有一个名为 ROUNDUP 的 function,这不是数学家,我会称之为真正的向上或至少对我来说更合乎逻辑,因为它使得像 0.5 这样的正值变成 1,像 -0.5 这样的负值变成 -1 . So in other words the Excel ROUNDUP do a C++ ceil equivalent on the 0.5 value, and C++ floor equivalent on the -0.5 value.因此,换句话说,Excel ROUNDUP 在 0.5 值上执行 C++ ceil 等效值,在 -0.5 值上执行 C++ 等效值。

Is there nothing built into C++ like that? C++ 中没有任何内置功能吗? Yes I know I can make my own function, but that defeats the reason I need this as a custom function that determines if number to be rounded is a positive or a negative, then needs an IF statement!是的,我知道我可以制作自己的 function,但这违背了我需要它作为自定义 function 的原因,它确定要四舍五入的数字是正数还是负数,然后需要一个 IF 语句!

There's not built in function to round away from zero. function 没有内置从零舍入。 But you can write your own without any obvious if statements.但是您可以编写自己的代码而无需任何明显的if语句。

double RoundAwayFromZero(double v) {
    auto s = std::copysign(1.0, v);
    return s * std::ceil(v * s);
}

This uses copysign to get a properly signed 1.0 value that is then used to make the value positive, round it away from 0 using ceil , then restore the proper sign to the result.这使用copysign来获取正确签名的 1.0 值,然后使用该值使该值变为正数,使用ceil将其从 0 舍入,然后将正确的符号恢复到结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM