简体   繁体   English

使用Boost在C ++中舍入到最接近的数字?

[英]Rounding to nearest number in C++ using Boost?

Is there a way to round to the nearest number in the Boost library? 有没有办法在Boost库中舍入到最接近的数字? I mean any number, 2's, 5's, 17's and so on and so forth. 我的意思是任何数字,2个,5个,17个等等等等。

Or is there another way to do it? 或者还有另一种方法吗?

You can use lround available in C99. 您可以使用C99中的lround

#include <cmath>
#include <iostream>

int main() {
  cout << lround(1.4) << "\n";
  cout << lround(1.5) << "\n";
  cout << lround(1.6) << "\n";
}

(outputs 1, 2, 2). (输出1,2,2)。

Check your compiler documentation if and/or how you need to enable C99 support. 检查编译器文档是否和/或如何启用C99支持。

Boost Rounding Functions 提升舍入功能

For example: 例如:

#include <boost/math/special_functions/round.hpp>
#include <iostream>
#include <ostream>
using namespace std;

int main()
{
    using boost::math::lround;
    cout << lround(0.0) << endl;
    cout << lround(0.4) << endl;
    cout << lround(0.5) << endl;
    cout << lround(0.6) << endl;
    cout << lround(-0.4) << endl;
    cout << lround(-0.5) << endl;
    cout << lround(-0.6) << endl;
}

Output is: 输出是:

0
0
1
1
0
-1
-1
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;

You actually don't need Boost at all, just the C library included in the C++ library. 实际上你根本不需要Boost,只需要C ++库中包含的C库。 Specifically, you need to include the cmath header: 具体来说,您需要包含cmath标头:

Round up a number: ceil(): http://www.cplusplus.com/reference/clibrary/cmath/ceil/ 汇总一个数字:ceil(): http ://www.cplusplus.com/reference/clibrary/cmath/ceil/

Round down a number: floor(): http://www.cplusplus.com/reference/clibrary/cmath/floor/ 向下舍入一个数字:floor(): http//www.cplusplus.com/reference/clibrary/cmath/floor/

You can write your own round function then: 您可以编写自己的循环函数:

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

double roundFloat(double x)
{
    double base = floor( x );

    if ( x > ( base + 0.5 ) )
            return ceil( x );
    else    return base;
}

int main()
{
    std::string strInput;
    double input;

    printf( "Type a number: " );
    std::getline( std::cin, strInput );
    input = std::atof( strInput.c_str() );

    printf( "\nRounded value is: %7.2f\n", roundFloat( input ) );

    return EXIT_SUCCESS;
}

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

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