round() for float in C++

后端 未结 22 1653
时光取名叫无心
时光取名叫无心 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:22

    I did this:

    #include 
    
    using namespace std;
    
    double roundh(double number, int place){
    
        /* place = decimal point. Putting in 0 will make it round to whole
                                  number. putting in 1 will round to the
                                  tenths digit.
        */
    
        number *= 10^place;
        int istack = (int)floor(number);
        int out = number-istack;
        if (out < 0.5){
            floor(number);
            number /= 10^place;
            return number;
        }
        if (out > 0.4) {
            ceil(number);
            number /= 10^place;
            return number;
        }
    }
    

提交回复
热议问题