C 中用于浮点数的 round()

新手上路,请多包涵

我需要一个简单的浮点舍入函数,因此:

 double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

我可以在 math.h 中找到 ceil()floor() - 但不是 round()

它是否以另一个名称出现在标准 C++ 库中,还是丢失了?

原文由 Roddy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 689
2 个回答

它从 cmath 中的 C++11 开始可用(根据 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

 #include <cmath>
#include <iostream>

int main(int argc, char** argv) {
  std::cout << "round(0.5):\t" << round(0.5) << std::endl;
  std::cout << "round(-0.5):\t" << round(-0.5) << std::endl;
  std::cout << "round(1.4):\t" << round(1.4) << std::endl;
  std::cout << "round(-1.4):\t" << round(-1.4) << std::endl;
  std::cout << "round(1.6):\t" << round(1.6) << std::endl;
  std::cout << "round(-1.6):\t" << round(-1.6) << std::endl;
  return 0;
}

输出:

 round(0.5):  1
round(-0.5): -1
round(1.4):  1
round(-1.4): -1
round(1.6):  2
round(-1.6): -2

原文由 schibum 发布,翻译遵循 CC BY-SA 3.0 许可协议

round_f 用于带有数学的 ARM

 static inline float round_f(float value)
{
    float rep;
    asm volatile ("vrinta.f32 %0,%1" : "=t"(rep) : "t"(value));
    return rep;
}

round_f 用于没有数学的 ARM

 union f__raw {
    struct {
        uint32_t massa  :23;
        uint32_t order  :8;
        uint32_t sign   :1;
    };
    int32_t     i_raw;
    float       f_raw;
};

float round_f(float value)
{
    union f__raw raw;
    int32_t exx;
    uint32_t ex_mask;
    raw.f_raw = value;
    exx = raw.order - 126;
    if (exx < 0) {
        raw.i_raw &= 0x80000000;
    } else if (exx < 24) {
        ex_mask = 0x00ffffff >> exx;
        raw.i_raw += 0x00800000 >> exx;
        if (exx == 0) ex_mask >>= 1;
        raw.i_raw &= ~ex_mask;
    };
    return  raw.f_raw;
};

原文由 AVI-crak Home 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题