round() for float in C++

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

    It's available since C++11 in cmath (according to http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf)

    #include 
    #include 
    
    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;
    }
    

    Output:

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

提交回复
热议问题