round() for float in C++

后端 未结 22 1178
时光取名叫无心
时光取名叫无心 2020-11-22 03:01

I need a simple floating point rounding function, thus:

double round(double);

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

I can find

22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:25

    I use the following implementation of round in asm for x86 architecture and MS VS specific C++:

    __forceinline int Round(const double v)
    {
        int r;
        __asm
        {
            FLD     v
            FISTP   r
            FWAIT
        };
        return r;
    }
    

    UPD: to return double value

    __forceinline double dround(const double v)
    {
        double r;
        __asm
        {
            FLD     v
            FRNDINT
            FSTP    r
            FWAIT
        };
        return r;
    }
    

    Output:

    dround(0.1): 0.000000000000000
    dround(-0.1): -0.000000000000000
    dround(0.9): 1.000000000000000
    dround(-0.9): -1.000000000000000
    dround(1.1): 1.000000000000000
    dround(-1.1): -1.000000000000000
    dround(0.49999999999999994): 0.000000000000000
    dround(-0.49999999999999994): -0.000000000000000
    dround(0.5): 0.000000000000000
    dround(-0.5): -0.000000000000000
    

提交回复
热议问题